package com.ctshk.rpc.order.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.constant.CurrencyIdCode;
import com.ctshk.common.dto.Result;
import com.ctshk.common.dto.payment.CallPayDTO;
import com.ctshk.common.enums.Currency;
import com.ctshk.common.enums.*;
import com.ctshk.common.enums.payment.PayCurrency;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.req.pay.NotifyConsumeReq;
import com.ctshk.common.utils.DateUtil;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.booking.enums.SupplierReserveTypeEnum;
import com.ctshk.rpc.booking.req.system.commodity.add.SupplierOrderSystemCommodityAddReq;
import com.ctshk.rpc.booking.req.system.commodity.add.SupplierSystemOrderCommodityAddReq;
import com.ctshk.rpc.booking.req.system.commodity.add.SupplierSystemOrderCommodityDetailAddReq;
import com.ctshk.rpc.booking.service.ISupplierOrderService;
import com.ctshk.rpc.finance.json.FileJson;
import com.ctshk.rpc.finance.req.bill.BillAddCollectionReq;
import com.ctshk.rpc.finance.req.onaccount.RollBackQuotaReq;
import com.ctshk.rpc.finance.service.IFinanceBillService;
import com.ctshk.rpc.finance.service.IFinanceOnAccountCurrencyQuotaService;
import com.ctshk.rpc.goods.service.IFreightTemplateService;
import com.ctshk.rpc.iotc.dto.OperateBankPreferenceQueryDTO;
import com.ctshk.rpc.iotc.req.OperateBankConformQueryReq;
import com.ctshk.rpc.iotc.req.OperateBankDeductReq;
import com.ctshk.rpc.iotc.service.IOperateBankPreferenceService;
import com.ctshk.rpc.order.goods.dto.*;
import com.ctshk.rpc.order.goods.entity.*;
import com.ctshk.rpc.order.goods.mapper.*;
import com.ctshk.rpc.order.goods.req.*;
import com.ctshk.rpc.order.goods.req.conmodity.CommodityCostSingleReq;
import com.ctshk.rpc.order.goods.req.conmodity.OrderCommodityRefundCancelReq;
import com.ctshk.rpc.order.goods.service.ICommodityService;
import com.ctshk.rpc.order.goods.service.IOrderService;
import com.ctshk.rpc.payment.enums.PayOrderStatus;
import com.ctshk.rpc.payment.enums.PaymentMethod;
import com.ctshk.rpc.payment.req.CallPayReq;
import com.ctshk.rpc.payment.service.IPayService;
import com.ctshk.rpc.system.dto.MainDataCurrencyQueryDTO;
import com.ctshk.rpc.system.dto.SysDepartmentDTO;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.req.DispatchOrderRuleGetUserReq;
import com.ctshk.rpc.system.req.MainDataCurrencyUpdateStatusReq;
import com.ctshk.rpc.system.service.*;
import com.ctshk.rpc.user.service.IOrderEsService;
import com.ctshk.rpc.user.service.IUserService;
import com.ctshk.rpc.workflow.dto.ApprovalCheckDTO;
import com.ctshk.rpc.workflow.dto.ApprovalStartDTO;
import com.ctshk.rpc.workflow.service.ISysApprovalService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author 姜斌文
 * @since 2021-04-19
 */
@Slf4j
@DubboService
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    /**
     * 工作流服务
     */
    @DubboReference
    private ISysApprovalService sysApprovalService;
    @DubboReference
    private ICommodityService commodityService;

    @DubboReference
    private ISysDepartmentService sysDepartmentService;
    @DubboReference
    private IFreightTemplateService freightTemplateService;
    @DubboReference
    private ISysUserService sysUserService;
    @DubboReference
    private IMainDataCurrencyService mainDataCurrencyService;
    @DubboReference
    private IOperateBankPreferenceService operateBankPreferenceService;

    @DubboReference
    private ISupplierOrderService supplierOrderService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderCommodityMapper orderCommodityMapper;
    @Autowired
    private OrderShipperInfoMapper shipperInfoMapper;
    @Autowired
    private OrderCommodityCollectionMapper orderCommodityCollectionMapper;
    @Autowired
    private OrderCommodityRefundMapper orderCommodityRefundMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @DubboReference
    private IFinanceBillService financeBillService;

    @DubboReference
    private IPayService iPayService;

    @DubboReference
    private IUserService userService;

    @DubboReference
    private IFinanceBillService iFinanceBillService;

    @DubboReference
    private IDispatchOrderRuleService dispatchOrderRuleService;

    @Autowired
    private OrderConsigneeInfoMapper orderConsigneeInfoMapper;

    @Autowired
    private ShoppingShopStoreUserMapper shoppingShopStoreUserMapper;

    @Autowired
    private OrderShipperInfoMapper orderShipperInfoMapper;

    @Autowired
    private CommodityMapper commodityMapper;

    @DubboReference
    private IFinanceOnAccountCurrencyQuotaService onAccountCurrencyQuotaService;

    @DubboReference
    private ISysPermissionService sysPermissionService;

    @DubboReference
    private IOrderEsService orderEsService;

    @DubboReference
    private IOrderService orderService;

    @Value("${schedule.config.domain}")
    private String domain;

    @Value("${schedule.config.app-name}")
    private String appName;

    @Value("${schedule.config.password}")
    private String password;

    @Value("${schedule.job-id.order.goods}")
    private long jobId;

    @Override
    public Result rejectPayment(String collectionNumber, Long userId, String msg) {
        log.info("【中旅到家商城订单收款-财务驳回收款】方法入参,collectionNumber:{},msg:{},userId:{}", collectionNumber, msg, userId);
        OrderCommodityCollection orderCommodityCollection = orderCommodityCollectionMapper.findOrderCommodityCollectionByCollectionNumber(collectionNumber);
        if (null == orderCommodityCollection) {
            log.error("【中旅到家商城--订单收款记录不存在】");
            return Result.failed(SystemError.MALL_MERCHANDISE_23039);
        }
        if (Objects.equals(orderCommodityCollection.getStatus(), OrderCollectionStatus.REJECT.getCode())) {
            log.error("【中旅到家商城--订单收款记录的状态必须不等于\"已驳回\"】");
            return Result.failed(SystemError.MALL_MERCHANDISE_23040);
        }
        // 状态为"已驳回"
        orderCommodityCollection.setStatus(OrderCollectionStatus.REJECT.getCode());
        // 驳回信息
        orderCommodityCollection.setRejectInfo(msg);
        // 修改的用户
        orderCommodityCollection.setModifiedId(userId);
        // 修改时间
        orderCommodityCollection.setGmtModified(LocalDateTime.now());
        orderCommodityCollectionMapper.updateCommodityCollectionById(orderCommodityCollection);
        return Result.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long addOrder(OrderAddReq addReq, TokenUser tokenUser) throws Exception {
        Long userId = tokenUser.getId();
        LocalDateTime now = LocalDateTime.now();
        checkAddOrderParam(addReq);
        Order order = new Order();
        BeanUtils.copyProperties(addReq, order);

        // 查询产品信息 (预订服务费类型，预订服务费)
        if (addReq != null && addReq.getCommodityId() != null) {
            Commodity commodity = commodityMapper.selectCommodityById(String.valueOf(addReq.getCommodityId()));
            if (commodity != null) {
                order.setRefundServiceChargeType(commodity.getRefundServiceChargeType());
                order.setRefundServiceCharge(commodity.getRefundServiceCharge());
            }
        }

        order.setId(SnowflakeIdWorker.nextId());
        order.setOrderStatus(1); // 订单状态:1：待付款; 2：待发货; 3：待收货; 4：已完成; 5：已取消
        order.setWriteOffStatus(1); // 核销状态:1：未核销; 2：已核销
        // 只有门店自提才创建核销码
        if (order.getDeliveryMode() != null && order.getDeliveryMode() == 2) {
            // 生成核銷碼：年後2位+月日後3位数+3位随机数，例如：21+318+323，共計8位
            order.setOrderWriteOffNumber(generateOrderWriteOffNumber(now));
//            order.setWriteOffStatus(1);
        }
        order.setPaymentStatus(1); // 付款状态:1：待支付;2：已付款
        if (null == addReq.getUserId()) { // 下单人为空，默认为当前登入人
            order.setUserId(userId);
            order.setUserName(tokenUser.getUsername());
        }
        order.setCreateId(userId);
        order.setGmtCreate(now);
        order.setModifiedId(userId);
        order.setGmtModified(now);
        order.setIsDeleted(IsDeletedCode.NO.getCode());
        // 生成銷售編號：S+部門代碼+員工編號+年後2位+月日4位+3位隨機數字
        generateOrderNumberRule(order, tokenUser, now);
        // 生成付款到期时间
        order.setPayExpireDate(LocalDateTime.now().plusMinutes(30));
        order.setSaleUserId(tokenUser.getId());
        order.setSaleUserName(tokenUser.getNickname());
        order.setSourceId(Long.parseLong(OrderSource.CPM.getCode().toString())); // 订单来源id
        order.setSourceName(OrderSource.CPM.getMsg()); // 订单来源名称
        order.setProductType(1); // 产品类型
        order.setBusinessType(1); // 业务类型
        order.setSourceChannel(1); // 订单来源类型
        orderMapper.insertOrder(order);

        OrderConsigneeInfo orderConsigneeInfo = new OrderConsigneeInfo();
        // 用户下单时选择-1：物流配送(订单收货人信息表);
        if (null != addReq.getDeliveryMode() && addReq.getDeliveryMode().intValue() == 1) {
            // 配送方式：用户下单时选择-1：物流配送(订单收货人信息表); 2：门店自提（订单提货人信息表）
            OrderConsigneeInfoReq orderConsigneeInfoReq = addReq.getOrderConsigneeInfoReq();
            BeanUtils.copyProperties(orderConsigneeInfoReq, orderConsigneeInfo);
            orderConsigneeInfo.setOrderId(order.getId());
            orderConsigneeInfo.setCreateId(order.getCreateId());
            orderConsigneeInfo.setGmtCreate(order.getGmtCreate());
            orderConsigneeInfo.setModifiedId(order.getModifiedId());
            orderConsigneeInfo.setGmtModified(order.getGmtModified());
            orderConsigneeInfo.setIsDeleted(IsDeletedCode.NO.getCode());
            orderConsigneeInfoMapper.insert(orderConsigneeInfo);

        } else if (null != addReq.getDeliveryMode() && addReq.getDeliveryMode().intValue() == 2) { //  2：门店自提（订单提货人信息表）
            // 配送方式：用户下单时选择-1：物流配送(订单收货人信息表); 2：门店自提（订单提货人信息表）
            OrderShipperInfoReq orderShipperInfoReq = addReq.getOrderShipperInfoReq();
            orderShipperInfoReq.setOrderId(order.getId());
            orderShipperInfoReq.setCreateId(order.getCreateId());
            orderShipperInfoReq.setGmtCreate(order.getGmtCreate());
            orderShipperInfoReq.setModifiedId(order.getModifiedId());
            orderShipperInfoReq.setGmtModified(order.getGmtModified());
            orderShipperInfoReq.setIsDeleted(IsDeletedCode.NO.getCode());
            OrderShipperInfo orderShipperInfo = new OrderShipperInfo();
            BeanUtils.copyProperties(orderShipperInfoReq, orderShipperInfo);
            shipperInfoMapper.insertShipperInfo(orderShipperInfo);
        }

        // 订单商品,商品具体信息列表
        List<OrderCommodityReq> orderCommodityReqs = addReq.getOrderCommodityReqList();
        List<OrderCommodity> orderCommodityReqList = new ArrayList<OrderCommodity>();
        Long templateId = 0L;
        List<Double> firstArticles = new ArrayList<>();
        BigDecimal orderAmount = new BigDecimal(0);
        for (OrderCommodityReq commodityReqs : orderCommodityReqs) {
            Result<CommodityDTO> commodity = commodityService.findCommodityById(commodityReqs.getCommodityId());
            if (commodity.getCode() == 0 && commodity.getMsg().equalsIgnoreCase("成功")) {
                com.ctshk.rpc.order.goods.dto.CommodityDTO commodityDTO = commodity.getData(); // 商品详细信息
                templateId = commodityDTO.getFreightTemplateId(); // 模板ID
                List<com.ctshk.rpc.order.goods.req.conmodity.CommodityCostSingleReq> commodityCostSingleReqList = commodityDTO.getCommodityCostReqList();
                BigDecimal singlePrice = new BigDecimal(0);
                String commodityPictureUrl = "";
                Long commodityCostAttributeId = 0L;
                if (commodityCostSingleReqList != null) {
                    for (CommodityCostSingleReq commodityCostSingleReq : commodityCostSingleReqList) {
                        if (commodityReqs.getCommodityCostId() != null) {
                            if (commodityCostSingleReq.getId().longValue() == commodityReqs.getCommodityCostId().longValue()) {
                                if (commodityCostSingleReq.getStock() <= 0) {
                                    throw new BusinessException(SystemError.MALL_MERCHANDISE_23001);
                                }
                                commodityPictureUrl = commodityCostSingleReq.getPictureUrl();
                                firstArticles.add(commodityCostSingleReq.getWeight());
                                singlePrice = commodityCostSingleReq.getPrice();
                                commodityCostAttributeId = commodityCostSingleReq.getCostAttributeId();
                                break;
                            }
                        }
                    }
                }
                OrderCommodity orderCommodity = new OrderCommodity(); // 订单商品表
                BeanUtils.copyProperties(commodityReqs, orderCommodity);
                orderCommodity.setCommodityId(commodityDTO.getId()); // 商品ID
                orderCommodity.setCommodityName(commodityDTO.getCommodityName()); // 商品名稱
                orderCommodity.setOrderId(order.getId()); // 訂單ID
                orderCommodity.setCommodityPrice(singlePrice); // 商品單價
                BigDecimal number = new BigDecimal(orderCommodity.getNumber().toString());
                BigDecimal totalPirce = singlePrice.multiply(number);
                orderCommodity.setCommodityTotalPrice(addReq.getOrderAmount()); // 單條數據 * 購買數量 = 單條商品總金額
                orderAmount = orderAmount.add(orderCommodity.getCommodityTotalPrice());
                //LocalDateTime timePlusThirtyMin = now.plusMinutes(30); // 當前時間 +30 分鐘。
                //orderCommodity.setEffectiveTime(timePlusThirtyMin); // 訂單支付時間30分鐘有效期
                orderCommodity.setCreateId(order.getCreateId());
                orderCommodity.setGmtCreate(order.getGmtCreate());
                orderCommodity.setModifiedId(order.getModifiedId());
                orderCommodity.setGmtModified(order.getGmtModified());
                orderCommodity.setIsDeleted(IsDeletedCode.NO.getCode());
                orderCommodity.setCommodityPictureUrl(commodityPictureUrl);
                orderCommodity.setCommodityCostAttributeId(commodityCostAttributeId);
                log.info("【中旅到家--门店订单--新增】，入参为:{}", JSON.toJSONString(orderCommodity));
                orderCommodityMapper.insert(orderCommodity);
            } else {
                throw new BusinessException(SystemError.MALL_MERCHANDISE_23002);
            }
        }
        // 根据运费模板，獲取運費费用
        if (addReq.getDeliveryMode() == 1) {
            JSONObject frachtpreisObj = freightTemplateService.getFreightByWeightOrPieceCount(templateId, firstArticles, orderConsigneeInfo.getConsigneeAreaId());
            if (frachtpreisObj != null && !frachtpreisObj.equals("{}")) {
                if (null != frachtpreisObj.getString("error") &&
                        !"".equalsIgnoreCase(frachtpreisObj.getString("error"))) {
                    throw new BusinessException(SystemError.MALL_MERCHANDISE_23003);
                }
                if (null == frachtpreisObj.getString("frachtpreis") || "".equalsIgnoreCase(frachtpreisObj.getString("frachtpreis"))) {
                    throw new BusinessException(SystemError.MALL_MERCHANDISE_23003);
                }
                order.setFreightAmount(new BigDecimal(frachtpreisObj.getString("frachtpreis")));
            }
        }

        // 将运费获取累计到应收金额中
        if (orderAmount.compareTo(new BigDecimal("0")) == 1) {
            if (order.getFreightAmount().compareTo(new BigDecimal("0")) == 1) { // 运费大于0,累计到应收金额中
                orderAmount = orderAmount.add(order.getFreightAmount());
            }
            order.setOrderAmount(orderAmount);
        }
        orderMapper.updateById(order);
        return order.getId();
    }

    /**
     * 获取销售人并生成销售编号
     */
    private UserDTO getSaleMan() {
        DispatchOrderRuleGetUserReq dispatchOrderRuleGetUserReq = new DispatchOrderRuleGetUserReq();
        dispatchOrderRuleGetUserReq.setBusinessTypeId(SystemBusinessType.COMMODITY.getCode());
        dispatchOrderRuleGetUserReq.setCompanyType(CompanyType.HK_CT.getCode());
        Result<Long> result = dispatchOrderRuleService.getDispatchUserId(dispatchOrderRuleGetUserReq);
        if (!result.isSuccess()) {
            log.error("【中旅到家APP-提交订单】获取销售人失败:{},msg:{}", result.getCode(), result.getMsg());
            throw new BusinessException(SystemError.getDefined(result.getCode()));
        }
        UserDTO saleUser = sysUserService.queryCacheUser(result.getData());
        return saleUser;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<Long> addAppOrder(OrderAddReq addReq, Long userId) throws Exception {
        log.info("【中旅商城--APP新增订单】，入参为：orderReq:{},userId:{}", JSON.toJSONString(addReq), userId);
//        Long userId = tokenUser.getId();
        UserDTO tokenUser = null;
//        if (null == userId) {
        tokenUser = sysUserService.loadUserByParam("admin", 2);
//        } else {
//            tokenUser = userService.queryCacheUser(userId);
//        }
        LocalDateTime now = LocalDateTime.now();
        checkAddOrderParam(addReq);
        Order order = new Order();
        BeanUtils.copyProperties(addReq, order);
        order.setOrderStatus(1); // 订单状态:1：待付款; 2：待发货; 3：待收货; 4：已完成; 5：已取消
        order.setWriteOffStatus(1); // 核销状态:1：未核销; 2：已核销
        // 生成核銷碼：年後2位+月日後3位数+3位随机数，例如：21+318+323，共計8位
        order.setOrderWriteOffNumber(generateOrderWriteOffNumber(now));
        order.setPaymentStatus(1); // 付款状态:1：待支付;2：已付款
        if (null == addReq.getUserId()) { // 下单人为空，默认为当前登入人
            order.setUserId(userId);
            order.setUserName(tokenUser.getUsername());
        }
        order.setCreateId(userId);
        order.setGmtCreate(now);
        order.setModifiedId(userId);
        order.setGmtModified(now);
        order.setIsDeleted(IsDeletedCode.NO.getCode());
        // 生成銷售編號：S+部門代碼+員工編號+年後2位+月日4位+3位隨機數字
        generateAppOrderNumberRule(order, tokenUser, now);
//        order.setOrderNumber("admin");
        // TODO 生成查询编号,规则暂定，先生成随机六位数
        if (userId == null) {
            int searchCode = (int) ((Math.random() * 9 + 1) * 100000);
            order.setSearchCode(String.valueOf(searchCode));
        }

        // 获取销售人员
        UserDTO saleMan = getSaleMan();
        if (null != saleMan) {
            order.setSaleUserId(saleMan.getId());
            order.setSaleUserName(saleMan.getCnName());
        }
        order.setScheduledStatus(0); // 订阅状态-待确认
        order.setPaymentStatus(1); // 付款状态-代付款
        order.setOrderStatus(1); // 订单状态-代付款
        order.setReceiptUp(addReq.getReceiptUp()); //收据抬头
        order.setId(SnowflakeIdWorker.nextId()); // 订单id
        order.setPayExpireDate(now.plusMinutes(30)); // 付款到期时间

        log.info("【中旅商城--APP新增订单】order参数为:{}", JSON.toJSONString(order));
        orderMapper.insertOrder(order);

        OrderConsigneeInfo orderConsigneeInfo = new OrderConsigneeInfo();
        // 用户下单时选择-1：物流配送(订单收货人信息表);
        if (null != addReq.getDeliveryMode() && addReq.getDeliveryMode().intValue() == 1) {
            // 配送方式：用户下单时选择-1：物流配送(订单收货人信息表); 2：门店自提（订单提货人信息表）
            OrderConsigneeInfoReq orderConsigneeInfoReq = addReq.getOrderConsigneeInfoReq();
            BeanUtils.copyProperties(orderConsigneeInfoReq, orderConsigneeInfo);
            orderConsigneeInfo.setId(IdWorker.getId());
            orderConsigneeInfo.setOrderId(order.getId());
            orderConsigneeInfo.setCreateId(order.getCreateId());
            orderConsigneeInfo.setGmtCreate(order.getGmtCreate());
            orderConsigneeInfo.setModifiedId(order.getModifiedId());
            orderConsigneeInfo.setGmtModified(order.getGmtModified());
            orderConsigneeInfo.setIsDeleted(IsDeletedCode.NO.getCode());
            log.info("【中旅商城--APP新增订单--新增订单收货人信息】orderConsigneeInfo入参为:{}", JSON.toJSONString(orderConsigneeInfo));
            orderConsigneeInfoMapper.insertConsigneeInfo(orderConsigneeInfo);

        } else if (null != addReq.getDeliveryMode() && addReq.getDeliveryMode().intValue() == 2) { //  2：门店自提（订单提货人信息表）
            // 配送方式：用户下单时选择-1：物流配送(订单收货人信息表); 2：门店自提（订单提货人信息表）
            OrderShipperInfoReq orderShipperInfoReq = addReq.getOrderShipperInfoReq();
            orderShipperInfoReq.setOrderId(order.getId());
            orderShipperInfoReq.setCreateId(order.getCreateId());
            orderShipperInfoReq.setGmtCreate(order.getGmtCreate());
            orderShipperInfoReq.setModifiedId(order.getModifiedId());
            orderShipperInfoReq.setGmtModified(order.getGmtModified());
            orderShipperInfoReq.setIsDeleted(IsDeletedCode.NO.getCode());
            OrderShipperInfo orderShipperInfo = new OrderShipperInfo();
            BeanUtils.copyProperties(orderShipperInfoReq, orderShipperInfo);
            log.info("【中旅商城--APP新增订单--新增订单提货人信息】orderShipperInfo入参为:{}", JSON.toJSONString(orderShipperInfo));
            shipperInfoMapper.insertShipperInfo(orderShipperInfo);
        }

        // 订单商品,商品具体信息列表
        List<OrderCommodityReq> orderCommodityReqs = addReq.getOrderCommodityReqList();
        Long templateId = 0L;
        List<Double> firstArticles = new ArrayList<>();
        BigDecimal orderAmount = new BigDecimal(0);
        for (OrderCommodityReq commodityReqs : orderCommodityReqs) {
            Result<CommodityDTO> commodity = commodityService.findCommodityById(commodityReqs.getCommodityId());
            log.info("【中旅商城--APP新增订单--查询商品明细】返参为:{}", JSON.toJSONString(commodity));
            if (commodity.getCode() == 0 && commodity.getMsg().equalsIgnoreCase("成功")) {
                CommodityDTO commodityDTO = commodity.getData(); // 商品详细信息
                templateId = commodityDTO.getFreightTemplateId(); // 模板ID
                List<CommodityCostSingleReq> commodityCostSingleReqList = commodityDTO.getCommodityCostReqList();
                BigDecimal singlePrice = new BigDecimal(0);
                if (CollectionUtils.isNotEmpty(commodityCostSingleReqList)) {
                    // 多规格
                    for (CommodityCostSingleReq commodityCostSingleReq : commodityCostSingleReqList) {
                        if (commodityCostSingleReq.getCostAttributeId().longValue() == commodityReqs.getCommodityCostAttributeId().longValue()) {
                            if (commodityCostSingleReq.getStock() <= 0) {
                                throw new BusinessException(SystemError.MALL_MERCHANDISE_23001);
                            }
                            firstArticles.add(commodityCostSingleReq.getWeight());
                            singlePrice = commodityCostSingleReq.getCostPrice();
                            break;
                        }
                    }
                }
                OrderCommodity orderCommodity = new OrderCommodity(); // 订单商品表
                BeanUtils.copyProperties(commodityReqs, orderCommodity);
                orderCommodity.setCommodityId(commodityDTO.getId()); // 商品ID
                orderCommodity.setCommodityName(commodityDTO.getCommodityName()); // 商品名稱
                orderCommodity.setOrderId(order.getId()); // 訂單ID
                orderCommodity.setCommodityPrice(singlePrice); // 商品單價
                BigDecimal number = new BigDecimal(orderCommodity.getNumber().toString());
                BigDecimal totalPirce = singlePrice.multiply(number);
                orderCommodity.setCommodityTotalPrice(totalPirce); // 單條數據 * 購買數量 = 單條商品總金額
                orderAmount = orderAmount.add(orderCommodity.getCommodityTotalPrice());
//                LocalDateTime timePlusThirtyMin = now.plusMinutes(30); // 當前時間 +30 分鐘。
//                orderCommodity.setEffectiveTime(timePlusThirtyMin); // 訂單支付時間30分鐘有效期
                orderCommodity.setCreateId(order.getCreateId());
                orderCommodity.setGmtCreate(order.getGmtCreate());
                orderCommodity.setModifiedId(order.getModifiedId());
                orderCommodity.setGmtModified(order.getGmtModified());
                orderCommodity.setIsDeleted(IsDeletedCode.NO.getCode());
                log.info("【中旅商城--APP新增订单--新增商品订单信息】orderCommodity入参为:{}", JSON.toJSONString(orderCommodity));
                orderCommodityMapper.insertOrderCommodity(orderCommodity);
            } else {
                throw new BusinessException(SystemError.MALL_MERCHANDISE_23002);
            }
        }
        // 根据运费模板，獲取運費费用
        if (addReq.getDeliveryMode() == 1) {
            log.info("【中旅商城--APP新增订单--獲取運費费用】入参为：freightTemplateId:{},firstArticles:{},consigneeAreaId:{}", templateId, JSON.toJSONString(firstArticles), orderConsigneeInfo.getConsigneeAreaId());
            JSONObject frachtpreisObj = freightTemplateService.getFreightByWeightOrPieceCount(templateId, firstArticles, orderConsigneeInfo.getConsigneeAreaId());
            log.info("【中旅商城--APP新增订单--獲取運費费用】返参为:{}", JSON.toJSONString(frachtpreisObj));
            if (frachtpreisObj != null && !frachtpreisObj.equals("{}")) {
                if (null != frachtpreisObj.getString("error") &&
                        !"".equalsIgnoreCase(frachtpreisObj.getString("error"))) {
                    throw new BusinessException(SystemError.MALL_MERCHANDISE_23003);
                }
                if (null == frachtpreisObj.getString("frachtpreis") || "".equalsIgnoreCase(frachtpreisObj.getString("frachtpreis"))) {
                    throw new BusinessException(SystemError.MALL_MERCHANDISE_23003);
                }
                // 运费金额、运费模板
                order.setFreightAmount(new BigDecimal(frachtpreisObj.getString("frachtpreis")));
            }
        }

        // 将运费获取累计到应收金额中
        if (orderAmount.compareTo(new BigDecimal("0")) == 1) {
            if (order.getFreightAmount().compareTo(new BigDecimal("0")) == 1) { // 运费大于0,累计到应收金额中
                orderAmount = orderAmount.add(order.getFreightAmount());
            }
            order.setOrderAmount(orderAmount);
        }
        log.info("【中旅商城--APP更新订单】order参数为:{}", JSON.toJSONString(order));
        orderMapper.updateOrderById(order);
        sendOrderToAppUser(order.getId());
        return Result.success(order.getId());

        /**
         * 执行完毕，增加订单判断支付超时任务
         */
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("id", order.getId());
//        long delayMs = 10000 * 18;
//        log.info("【商品订单-提交订单】提交订单成功，启动定时任务:{},appName:{},time:{}", domain, appName, delayMs);
//        try {
//            OhMyClient taskClient = new OhMyClient(domain, appName, password);
//            ResultDTO<Long> resultDTO = taskClient.runJob(jobId, jsonObject.toJSONString(), delayMs);
//
//            if (resultDTO.isSuccess()) {
//                // 任务执行成功,过期时间*2是防止任务启动时redis数据已过期
//                redisTemplate.opsForValue().set(RedisConstants.ORDER_INSTANCELD_KEY + order.getId(), resultDTO.getData(), delayMs * 2, TimeUnit.MILLISECONDS);
//            }
//        } catch (Exception e) {
//            log.error("【商品订单-提交订单】提交订单失败，启动定时任务失败", e);
//            throw new BusinessException(SystemError.MALL_MERCHANDISE_23037);
//        }
    }

    @Override
    public Result payPlatform(Long oderId, Integer code, Long shopId) {
        if (null == oderId) {
            throw new BusinessException(SystemError.SYS_402);
        }
        // 查询订单
        Order order = orderMapper.selectOrderById(oderId);
        if (null == order) {
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23033);
        }

        // 平台支付
//        PayCommonReq req = new PayCommonReq();
//        req.setOrderNumber(order.getOrderNumber()); //订单编号
//        req.setNotifyUrl("/app/goods/order/commodity/pay/payCallback"); //回调网关
//        // 获取订单创建时间往后延迟30分钟
//        LocalDateTime gmtCreate = order.getGmtCreate().plusMinutes(30);
//        req.setOrderValidTime(gmtCreate);  // 有效时间
//        req.setSubject(SupplierReserveTypeEnum.COMMODITY.getName()); // 主题
//        req.setSubject("商品付款");
//        req.setBody("商品购买");
//        req.setCurrency(PayCurrency.HKD); // 默认港币
//        req.setTotalFee(order.getOrderAmount()); // 订单金额
//        req.setPaymentMethod(PaymentMethod.getByCode(code)); //支付方式
        CallPayReq callPayReq = new CallPayReq();
        log.info("【中旅商城APP端支付】----支付入参：{}", JSON.toJSONString(callPayReq));
        callPayReq.setId(order.getId());
        callPayReq.setBusinessTypeId(SystemBusinessType.COMMODITY.getCode());
        callPayReq.setPaymentMethodCode(PaymentMethod.getByCode(code).getCode());
        Result pay = iPayService.callPay(callPayReq);
        log.info("【中旅商城APP端支付】----支付回参：{}", JSON.toJSONString(pay));
        if (!pay.isSuccess() || pay.getData() == null) {
            Result.failed(SystemError.PAY_22001);
        }
        return Result.success(pay.getData());
    }

    /**
     * 生成銷售編號：S+部門代碼+員工編號+年後2位+月日4位+3位隨機數字
     *
     * @param order     订单对象
     * @param tokenUser 用户对象
     * @param now       当前日期
     */
    private void generateOrderNumberRule(Order order, TokenUser tokenUser, LocalDateTime now) {
        //部门代码
        SysDepartmentDTO sysDepartmentDTO = sysDepartmentService.queryByUserId(tokenUser.getId());

        //生成规则：S+部門代碼+員工編號+年後2位+月日4位+3位隨機數字
        StringBuffer sb = new StringBuffer();
        sb.append("S");
        if (sysDepartmentDTO == null || StringUtils.isNotBlank(sysDepartmentDTO.getDeptCode())) {
            sb.append(sysDepartmentDTO.getDeptCode());
        }
        sb.append(tokenUser.getId());
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyMMdd");
        String localTime = df.format(now);
        sb.append(localTime);

        // 最后生成3位随机数，没有硬性要求，000-999，故取了100-999
        Random random = new Random();
        int s = random.nextInt(999) % (999 - 100 + 1) + 100;
        sb.append(s);
        order.setOrderNumber(sb.toString());
    }

    /**
     * C端生成銷售編號：S+部門代碼+員工編號+年後2位+月日4位+3位隨機數字
     *
     * @param order
     * @param tokenUser
     * @param now
     */
    private void generateAppOrderNumberRule(Order order, UserDTO tokenUser, LocalDateTime now) {
        //部门代码
        SysDepartmentDTO sysDepartmentDTO = sysDepartmentService.queryByUserId(tokenUser.getId());

        //生成规则：S+部門代碼+員工編號+年後2位+月日4位+3位隨機數字
        StringBuffer sb = new StringBuffer();
        sb.append("S");
        if (sysDepartmentDTO == null || StringUtils.isNotBlank(sysDepartmentDTO.getDeptCode())) {
            sb.append(sysDepartmentDTO.getDeptCode());
        }
        sb.append(tokenUser.getId());
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyMMdd");
        String localTime = df.format(now);
        sb.append(localTime);

        // 最后生成3位随机数，没有硬性要求，000-999，故取了100-999
        Random random = new Random();
        int s = random.nextInt(999) % (999 - 100 + 1) + 100;
        sb.append(s);
        order.setOrderNumber(sb.toString());
    }

    /**
     * 生成退款單號：單號規則：TKD+年後2位+月日4位+時分秒6位+2位隨機數字；
     *
     * @param now 当前日期
     * @return String 退款单号
     */
    private String generateRefundNumberRule(LocalDateTime now) {
        //生成规则：TKD+年後2位+月日4位+時分秒6位+2位隨機數字；
        StringBuffer sb = new StringBuffer();
        sb.append("TKD");
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyMMddhhMMss");
        String localTime = df.format(now);
        sb.append(localTime);
        // 最后生成2位随机数，没有硬性要求，00-99，故取了10-99
        Random random = new Random();
        int s = random.nextInt(99) % (99 - 10 + 1) + 10;
        sb.append(s);
        return sb.toString();
    }

    /**
     * 生成核銷碼：年後2位+月日後3位数+3位随机数，例如：21+318+323，共計8位
     *
     * @param now 当前日期
     * @return String 核銷碼号
     */
    private String generateOrderWriteOffNumber(LocalDateTime now) {
        //生成规则：TKD+年後2位+月日4位+時分秒6位+2位隨機數字；
        StringBuffer sb = new StringBuffer();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyMMdd");
        String localTime = df.format(now);
        String newTimeStr = localTime.substring(0, 2) + localTime.substring(3, localTime.length());
        sb.append(newTimeStr);
        // 最后生成3位随机数，没有硬性要求，000-999，故取了100-999
        Random random = new Random();
        int s = random.nextInt(999) % (999 - 100 + 1) + 100;
        sb.append(s);
        return sb.toString();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void payment(Long oderId, List<OrderCommodityCollectionReq> orderCommodityCollectionReqList, Long userId) {
        log.info("【中旅商城--订单支付--start】，入参为：oderId:{},orderCommodityCollectionReqList:{},userId:{}", oderId, JSON.toJSONString(orderCommodityCollectionReqList), userId);
        Order order = orderMapper.selectOrderById(oderId);
        if (order == null) {
            //订单不存在
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23033);
        }
        LocalDateTime nowLocalDateTime = LocalDateTime.now();

        log.info("【中旅商城--订单支付--查询商品订单】，入参为：{}", order.getId());
        List<OrderCommodity> orderCommodities = orderCommodityMapper.selectListByOrderId(order.getId());
        log.info("【中旅商城--订单支付--查询商品订单】，返回结果为：{}", JSON.toJSONString(orderCommodities));

        log.info("【中旅商城--订单支付--查询B端用户信息】，入参为：{}", userId);
        // 获取B端用户信息
        UserDTO userDTO = sysUserService.queryCacheUser(userId);
        log.info("【中旅商城--订单支付--查询B端用户信息】，返回结果为：{}", JSON.toJSONString(userDTO));

        order.setPaymentStatus(OrderPaymentStatus.ALREADY_PAYMENT.getCode());
//        if (order.getDeliveryMode() != null && order.getDeliveryMode() == 1) {
        // 订单状态:1：待付款; 2：待发货; 3：待收货; 4：已完成; 5：已取消
        if (order.getDeliveryMode().intValue() == 2) {
            order.setOrderStatus(6);
        } else {
            order.setOrderStatus(2);
        }
        // 付款状态:1：待支付;2：已付款
        order.setPaymentStatus(2);
        // 预订状态：1、确定预订 2、确认取消 3、待确认
        order.setScheduledStatus(1);
        // 取消状态 1、审批中 2、审批通过 3、审批未通过
        order.setCancelStatus(0);
//        }
        order.setModifiedId(userDTO.getId());
        order.setGmtModified(nowLocalDateTime);
        order.setPayMethod(orderCommodityCollectionReqList.get(0).getCollectionWay());
        orderMapper.updateOrderById(order);

        // 计算支付总金额和支付记录
        //是否使用银联优惠
        boolean useUnionpayDiscount = false;
        //订单金额(港币)=实收金额+积分抵扣+优惠券
        BigDecimal amountCountHKD = BigDecimal.ZERO;
        //实收金额(港币)
        BigDecimal readyMoney = BigDecimal.ZERO;
        List<OrderCommodityCollection> orderCommodityCollectionList = EntityUtil.copyList(orderCommodityCollectionReqList, OrderCommodityCollection.class);
        // 获取对应汇率，计算支付金额
        MainDataCurrencyQueryDTO currencyQueryDTO = null;
        List<BillAddCollectionReq> addCollectionReqs = new ArrayList<>();
        List<SupplierSystemOrderCommodityDetailAddReq> commodityDetailAddReqList = new ArrayList<>();
        List<FileJson> collectionVoucherJsonList = new ArrayList<>();
        try {
            for (OrderCommodityCollection orderCommodityCollection : orderCommodityCollectionList) {
                if (orderCommodityCollection.getCurrencyId() == null) {
                    //币种不能为空
                    throw new BusinessException(SystemError.AIREXPRESS_ORDER_60029);
                }
                // 获取对应汇率，计算支付金额
                currencyQueryDTO = getExchangeRateByName(orderCommodityCollection.getCurrencyId());
                // 门市兑换率
                BigDecimal marketExchangeRate = currencyQueryDTO.getMarketExchangeRate();
                // 港币金额
                BigDecimal amountHKD;
                if (orderCommodityCollection.getIsUnionpayDiscount() == 1) {
                    // 使用银联优惠
                    useAmountByBankReference(order, orderCommodityCollection, userDTO);
                    amountHKD = orderCommodityCollection.getCollectionAmount();
                    useUnionpayDiscount = true;
                } else {
                    amountHKD = orderCommodityCollection.getCollectionAmount().multiply(marketExchangeRate);
                    readyMoney = readyMoney.add(amountHKD);
                }
                amountCountHKD = amountCountHKD.add(amountHKD);
                String paymentNumber = generatorPaymentNumber(nowLocalDateTime);
                orderCommodityCollection.setId(SnowflakeIdWorker.nextId()); //id
                orderCommodityCollection.setOrderId(oderId); //订单id
                orderCommodityCollection.setCollectionNumber(paymentNumber); // 收款单号
                orderCommodityCollection.setCurrency(currencyQueryDTO.getCurrencyCode()); // 收款币种
                orderCommodityCollection.setStandardAmount(amountHKD);//本位币金额
                orderCommodityCollection.setStatus(OrderCollectionStatus.UN_REJECT.getCode()); // 未驳回状态
                orderCommodityCollection.setSalerId(userDTO.getId()); // 销售人id
                orderCommodityCollection.setCollectionWay(orderCommodityCollection.getCollectionWay()); // 支付方式
                orderCommodityCollection.setCollectionWayId(orderCommodityCollection.getCollectionWayId()); // 支付方式id
                orderCommodityCollection.setSalerName(userDTO.getFullName()); // 销售人名称
                orderCommodityCollection.setIsDeleted(IsDeletedCode.NO.getCode()); // 删除标识
                orderCommodityCollection.setCreateId(userDTO.getId()); // 账户id
                orderCommodityCollection.setGmtCreate(nowLocalDateTime); // 创建时间
                orderCommodityCollection.setModifiedId(userDTO.getId()); // 账户id
                orderCommodityCollection.setGmtModified(nowLocalDateTime); // 修改时间

                // 原本應該放在外圍checkAmount之後批量新增，由於批量有問題，暫時先單個新增
                orderCommodityCollectionMapper.insertOrderCommodityCollection(orderCommodityCollection);

                /*****************新增收款记录 start******************/
                BillAddCollectionReq billAddCollectionReq = new BillAddCollectionReq();
                // 收款单号
                billAddCollectionReq.setBillNumber(paymentNumber);
                // 业务类型
                billAddCollectionReq.setBusinessType(SystemBusinessType.COMMODITY.getCode());
                // 收款方式ID
                billAddCollectionReq.setCollectionWayId(orderCommodityCollection.getCollectionWayId());
                // 收款方式
                billAddCollectionReq.setCollectionWayName(orderCommodityCollection.getCollectionWay());
                // 收款类型ID
                billAddCollectionReq.setCollectionTypeId(CollectionTypeIdCode.FULL.getCode());
                // 收款类型
                billAddCollectionReq.setCollectionTypeName(CollectionTypeIdCode.FULL.getMsg());
                // 收款金额
                billAddCollectionReq.setCollectionAmount(readyMoney);
                // 币种ID
                billAddCollectionReq.setCurrencyId(currencyQueryDTO.getId());
                // 币种名称
                billAddCollectionReq.setCurrencyName(currencyQueryDTO.getCurrencyCode());
                // 汇率
                billAddCollectionReq.setExchangeRate(marketExchangeRate.doubleValue());
                // 收款时间
                billAddCollectionReq.setCollectionTime(LocalDateTime.now());
                // 收款JSON凭证
                collectionVoucherJsonList = JSON.parseArray(orderCommodityCollection.getCollectionCertificateJson(), FileJson.class);
                billAddCollectionReq.setCollectionVoucherJsonList(collectionVoucherJsonList);
                // 销售单号
                billAddCollectionReq.setSaleOrderNumber(order.getOrderNumber());
                // 销售单id
                billAddCollectionReq.setSaleOrderId(order.getId());
                // 产品id
                List<Long> productId = new ArrayList<>();
                productId.add(orderCommodities.get(0).getCommodityId());
                billAddCollectionReq.setProductId(productId);
                // 产品编号
                billAddCollectionReq.setProductNumber(orderCommodities.get(0).getCommodityNumber());
                // 产品名称
                billAddCollectionReq.setProductName(order.getCommodityName());
                // 资源信息列表 -- 商品名称
                List<String> resourceInfo = new ArrayList<>();
                resourceInfo.add(order.getCommodityName());
                billAddCollectionReq.setResourceInfo(resourceInfo);
                // 销售人id
                billAddCollectionReq.setSaleUserId(userDTO.getId());
                // 销售人名称
                billAddCollectionReq.setSaleUserName(userDTO.getFullName());
                // 销售部门ID
                billAddCollectionReq.setSaleDeptId(userDTO.getDeptId());
                // 用户id
                billAddCollectionReq.setUserId(userDTO.getId());

                addCollectionReqs.add(billAddCollectionReq);
                /*****************新增收款记录 end******************/

            }

            // 校验应收价格
            checkAmount(amountCountHKD, order.getOrderAmount());

            log.info("【中旅商城--订单支付--财务中心】，开始入参为：{}", JSON.toJSONString(addCollectionReqs));
            iFinanceBillService.addCollection(addCollectionReqs);
            log.info("【中旅商城--订单支付--财务中心】，调用成功");

            /**
             * 根据商品供应商信息生成供应商预订单
             */
            for (OrderCommodity orderCommodity : orderCommodities) {
                /*****************对接供应商 start******************/
                SupplierOrderSystemCommodityAddReq supplierOrderSystemCommodityAddReq = new SupplierOrderSystemCommodityAddReq();
                // 商品信息详情列表
                SupplierSystemOrderCommodityDetailAddReq systemOrderCommodityDetailAddReq = new SupplierSystemOrderCommodityDetailAddReq();
                // 所属订单ID
                systemOrderCommodityDetailAddReq.setOrderId(order.getId());
                // 基础信息表id
                systemOrderCommodityDetailAddReq.setAirExpressInfoId(0L);
                // 商品编号
                systemOrderCommodityDetailAddReq.setCommodityNumber(orderCommodity.getCommodityNumber());
                // 商品名称
                systemOrderCommodityDetailAddReq.setCommodityName(orderCommodity.getCommodityName());
                // 旅客名称，收货人
                systemOrderCommodityDetailAddReq.setPassengerName("");
                // 数量
                systemOrderCommodityDetailAddReq.setNumber(orderCommodity.getNumber());
                // 单价
                systemOrderCommodityDetailAddReq.setPrice(orderCommodity.getCommodityPrice());
                commodityDetailAddReqList.add(systemOrderCommodityDetailAddReq);
                log.info("【中旅商城--订单支付--查询商品信息】，入参为：{}", orderCommodity.getCommodityId());
                Result<CommodityDTO> commodityById = commodityService.findCommodityById(orderCommodity.getCommodityId());
                log.info("【中旅商城--订单支付--查询商品信息】，返回结果为：{}", JSON.toJSONString(commodityById.getData()));
                // 订单类型
                supplierOrderSystemCommodityAddReq.setOrderType(SystemBusinessType.COMMODITY.getCode());
                // 外挂单出票类型(1:门店出票,2:后台出票)
                supplierOrderSystemCommodityAddReq.setTicketMode(PluginTicketMode.BACKSTAGE_TICKET.getCode());
                // 所属团期ID
//        supplierOrderSystemCommodityAddReq.setScheduleId(0L);
                if (null != commodityById.getData()) {
                    // 供应商ID
                    supplierOrderSystemCommodityAddReq.setSupplierId(commodityById.getData().getSupplierId());
                    // 供应商名称
                    supplierOrderSystemCommodityAddReq.setSupplierName(commodityById.getData().getSupplierName());
                }
                // 供应商订单类型(1:普通订单,2:内部挂账订单)
                supplierOrderSystemCommodityAddReq.setSupplierOrderType("");
                // 供应商销售编号/部门ID(根据'供应商订单编号'显示，1：供应商销售编号，2：部门ID)
                supplierOrderSystemCommodityAddReq.setOriginalSaleNumber(userDTO.getDept());
                // 业务类型
                supplierOrderSystemCommodityAddReq.setBusinessType(SystemBusinessType.COMMODITY.getCode());
                // 销售方式
                supplierOrderSystemCommodityAddReq.setSaleType(SalesMethod.SINGLE_SALE.getCode());
                // 预订类型
                supplierOrderSystemCommodityAddReq.setReserveTypeId(SupplierReserveTypeEnum.COMMODITY.getId());
                // 预订状态
                supplierOrderSystemCommodityAddReq.setReserveStatus(OrderScheduledStatus.CONFIRM_RESERVE.getCode());
                // 产品类型 -- 人工录入写死
                supplierOrderSystemCommodityAddReq.setProductType(ProductType.MANUAL_ENTRY.getCode());
                // 资源所属部门ID(当前用户部门ID)
                supplierOrderSystemCommodityAddReq.setDepartmentId(userDTO.getDeptId());
                // 资源所属部门
                supplierOrderSystemCommodityAddReq.setDepartment(userDTO.getDept());
                // 销售单号(通用)不能为空---订单单号
                supplierOrderSystemCommodityAddReq.setSaleNumber(order.getOrderNumber());
                // 产品编号(通用)
                supplierOrderSystemCommodityAddReq.setProductNumber(orderCommodities.get(0).getCommodityNumber());
                // 产品名称(通用)不能为空
                supplierOrderSystemCommodityAddReq.setProductName(orderCommodities.get(0).getCommodityName());
                // 总金额
                supplierOrderSystemCommodityAddReq.setTotalFee(amountCountHKD);
                // 币种id
                supplierOrderSystemCommodityAddReq.setCurrencyId(currencyQueryDTO.getId());
                // 币种名称
                supplierOrderSystemCommodityAddReq.setCurrency(currencyQueryDTO.getCurrencyName());
                // 应付金额
                supplierOrderSystemCommodityAddReq.setPayableAmount(readyMoney);
                // 附件JSON
                net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(collectionVoucherJsonList);
                supplierOrderSystemCommodityAddReq.setFilesJson(jsonArray.toString());
                // 确认状态
                supplierOrderSystemCommodityAddReq.setConfirmStatus(1);
                // 确认时间
                supplierOrderSystemCommodityAddReq.setConfirmTime(LocalDateTime.now());
                // 供应商订单号
                supplierOrderSystemCommodityAddReq.setSupplierOrderNumber(order.getOrderNumber());
                // 使用资源编号
                supplierOrderSystemCommodityAddReq.setResourceNumber(orderCommodities.get(0).getCommodityNumber());
                // 使用资源产品名称
                supplierOrderSystemCommodityAddReq.setResourceProductName(orderCommodities.get(0).getCommodityName());
                // TODO 备注
//        supplierOrderSystemCommodityAddReq.setRemark("");
                // 商品信息列表
                List<SupplierSystemOrderCommodityAddReq> systemOrderCommodityAddReqList = new ArrayList<>();
                SupplierSystemOrderCommodityAddReq systemOrderCommodityAddReq = new SupplierSystemOrderCommodityAddReq();
                // 订单id
                systemOrderCommodityAddReq.setOrderId(order.getId());
                // TODO 供应商备注
//        systemOrderCommodityAddReq.setSupplierRemark();
                // TODO 客人备注
//        systemOrderCommodityAddReq.setCustomerRemark();
                // TODO 适合人群
//        systemOrderCommodityAddReq.setSuitablePeople();

                systemOrderCommodityAddReq.setSupplierSystemOrderCommodityDetailAddReqList(commodityDetailAddReqList);
                systemOrderCommodityAddReqList.add(systemOrderCommodityAddReq);
                supplierOrderSystemCommodityAddReq.setSupplierSystemOrderCommodityAddReqList(systemOrderCommodityAddReqList);
                log.info("【中旅商城--订单支付--供应商预订中心】，入参为：{}，userId:{}", JSON.toJSONString(supplierOrderSystemCommodityAddReq), JSON.toJSONString(userId));
                supplierOrderService.addSystemCommodity(supplierOrderSystemCommodityAddReq, userId);
                log.info("【中旅商城--订单支付--供应商预订中心】，调用成功");

                /*****************对接供应商 end******************/
            }

        } catch (Exception e) {
            log.error("财务中心或供应商预订中心接通失败,失败为:{}", e.getMessage());
            throw new BusinessException(SystemError.PAY_22001);
        }
        log.info("【中旅商城--订单支付--end】");
    }

    @Override
    public Result payment(NotifyConsumeReq notifyConsumeReq) throws Exception {
        log.info("【中旅商城--APP支付订单回调--start】,入参为：{}", JSON.toJSONString(notifyConsumeReq));
        try {

            // 根据订单号查询订单
            Order order = orderMapper.selectOrderByOrderNumber(notifyConsumeReq.getOrderNumber());
            if (Objects.isNull(order)) {
                return Result.failed(SystemError.MALL_MERCHANDISE_23033);
            }

            // 订单实收金额(港币)
            BigDecimal orderAmount = notifyConsumeReq.getAmount();
            BigDecimal amountCountHKD = BigDecimal.ZERO;//订单金额(港币)=实收金额+积分抵扣+优惠券
            PaymentMethod paymentMethod = PaymentMethod.getByCode(notifyConsumeReq.getPaymentMethod());

            // 获取订单收款明细
//            List<OrderCommodityPayDetailReq> orderCommodityPayDetailReqs = req.getOrderCommodityPayDetailReqList();
//            if (req.getIsUnionpayDiscount().intValue() == NumberConstant.ONE.getValue().intValue() &&
//                    (null == req.getUnionpayDiscountId() || req.getUnionpayDiscountId().intValue() < NumberConstant.ONE.getValue().intValue())) {
//                return Result.failed(SystemError.MALL_MERCHANDISE_23034);
//            }
            // 市场交换汇率
            BigDecimal marketExchangeRate = null;
            // 总金额
            BigDecimal totalMoney = BigDecimal.ZERO;

            // 订单收款明细
            List<OrderCommodityCollection> orderCommodityCollections = new ArrayList<>();

            LocalDateTime now = LocalDateTime.now();
            log.info("【中旅商城--APP支付接口--获取销售人】，入参为：order:{},code:{},now:{}", JSON.toJSONString(order), CompanyType.HK_CT.getCode(), now);
            // 随机获取销售人
            UserDTO saleMan = getSaleMan(order, CompanyType.HK_CT.getCode(), now);
            log.info("【中旅商城--APP支付接口--获取销售人】，返参为：UserDTO:{}", JSON.toJSONString(saleMan));

//            log.info("【中旅商城--APP支付接口--支付详情】，入参为：{}", JSON.toJSONString(orderCommodityPayDetailReqs));
//            for (OrderCommodityPayDetailReq orderCommodityPayDetailReq : orderCommodityPayDetailReqs) {
//                OrderCommodityCollection orderCommodityCollection = EntityUtil.copy(orderCommodityPayDetailReq, OrderCommodityCollection.class);
            OrderCommodityCollection orderCommodityCollection = new OrderCommodityCollection();
            // 生成收款单号
            String paymentNumber = generatorPaymentNumber(now);
            orderCommodityCollection.setCollectionNumber(paymentNumber);
            // 是否使用pos机（1、是 0、否）
            orderCommodityCollection.setIsPos(0);
            // 是否银联优惠
            orderCommodityCollection.setIsUnionpayDiscount(0);
            // 银联优惠id
            orderCommodityCollection.setUnionpayDiscountId(0L);
            // 订单商品收款明细id
            orderCommodityCollection.setId(SnowflakeIdWorker.nextId());
            // 订单id
            orderCommodityCollection.setOrderId(order.getId());
            // 创建人id
            orderCommodityCollection.setCreateId(saleMan.getId());
            // 更新人id
            orderCommodityCollection.setModifiedId(saleMan.getId());
            if (null != saleMan) {
                // 销售人员id
                orderCommodityCollection.setSalerId(saleMan.getId());
                // 销售人员名称
                orderCommodityCollection.setSalerName(saleMan.getUsername());
            }
            // 创建时间
            orderCommodityCollection.setGmtCreate(now);
            // 更新时间
            orderCommodityCollection.setGmtModified(now);
            // 删除标识 0 删除 1 未删除
            orderCommodityCollection.setIsDeleted(IsDeletedCode.NO.getCode());
            /******************************记录汇率 start*******************************/
            //获取汇率
            MainDataCurrencyQueryDTO exchangeRate = getExchangeRateByCurrencyId(Currency.HKD.getCode());
            //保证汇率存在
            if (exchangeRate == null || exchangeRate.getMarketExchangeRate() == null) {
                throw new BusinessException(SystemError.AIR_ORDER_15011, Currency.HKD.getCurrency());
            }
            marketExchangeRate = exchangeRate.getMarketExchangeRate();
            //当前汇率
            orderCommodityCollection.setExchangeRate(marketExchangeRate.doubleValue());
            //
            BigDecimal divide = orderAmount.multiply(marketExchangeRate)
                    // 去掉小数点多余的3位数
                    .setScale(3, BigDecimal.ROUND_DOWN);

            // 数据库表无汇率值和汇率转换之后的金额字段，看需求是否需要增加字段
            //计算金额
            // orderCommodityCollection.setExchangeRateAfterMoney(divide);
            //汇率ID
            // orderCommodityCollection.setExchangeRateId(exchangeRate.getId());

            //累计金额
            totalMoney = totalMoney.add(divide);
            /*****************************记录汇率 end********************************/
            // 付款账号
            orderCommodityCollection.setPayer(notifyConsumeReq.getPaymentAccount());
            // 收款金额
            orderCommodityCollection.setCollectionAmount(totalMoney);
            // 本位币金额
            orderCommodityCollection.setStandardAmount(totalMoney);
            // 状态为未驳回
            orderCommodityCollection.setStatus(OrderCollectionStatus.UN_REJECT.getCode());
            orderCommodityCollectionMapper.insertOrderCommodityCollection(orderCommodityCollection);
            orderCommodityCollections.add(orderCommodityCollection);
//            }

            /****************************************供应商预订单 start********************************************************/
            //订单详情的金额需要<=实付金额
            if (order.getOrderAmount().compareTo(totalMoney) > 0) {
                throw new BusinessException(SystemError.MALL_MERCHANDISE_23035);
            }

            // 查询订单商品信息
//        QueryWrapper<OrderCommodity> orderCommodityQueryWrapper = new QueryWrapper<>();
//        orderCommodityQueryWrapper.lambda().eq(OrderCommodity::getOrderId, req.getId());
//        List<OrderCommodity> orderCommodities = orderCommodityMapper.selectList(orderCommodityQueryWrapper);
            log.info("【中旅商城--APP订单支付--商品订单】，入参为：{}", JSON.toJSONString(order.getId()));
            List<OrderCommodity> orderCommodities = orderCommodityMapper.selectListByOrderId(order.getId());
            log.info("【中旅商城--APP订单支付--商品订单】，返参为：{}", JSON.toJSONString(orderCommodities));
            if (CollectionUtils.isEmpty(orderCommodities)) {
                throw new BusinessException(SystemError.MALL_MERCHANDISE_23033);
            }

//            List<Long> commodityIds = new ArrayList<>();
            // 获取商品明细
//            log.info("【中旅商城--APP订单支付--商品详情】，入参为：{}", JSON.toJSONString(commodityIds));
//            List<CommodityDTO> commodityDTOList = commodityService.selectCommodityDTOListByIds(commodityIds);
//            log.info("【中旅商城--APP订单支付--商品详情】，返参为：{}", JSON.toJSONString(commodityDTOList));
//            Map<Long, CommodityDTO> collectommodityMap = commodityDTOList.stream().collect(Collectors.toMap(CommodityDTO::getId, commodityDTO -> commodityDTO, (k1, k2) -> k1));
            // 查询商品信息
            for (OrderCommodity orderCommodity : orderCommodities) {
                SupplierOrderSystemCommodityAddReq supplierOrderSystemCommodityAddReq = new SupplierOrderSystemCommodityAddReq();
                CommodityDTO commodity = commodityMapper.findCommodityByCommodityId(orderCommodity.getCommodityId());
                if (null != commodity) {
                    supplierOrderSystemCommodityAddReq.setSupplierId(commodity.getSupplierId()); // 供应商id
                }
                supplierOrderSystemCommodityAddReq.setSupplierOrderType("1"); // 供应商订单类型
                supplierOrderSystemCommodityAddReq.setBusinessType(SystemBusinessType.COMMODITY.getCode()); // 业务类型
                supplierOrderSystemCommodityAddReq.setSaleType(SalesMethod.SINGLE_SALE.getCode()); // 销售方式
                supplierOrderSystemCommodityAddReq.setReserveTypeId(SupplierReserveTypeEnum.COMMODITY.getId()); // 预订类型
                supplierOrderSystemCommodityAddReq.setProductType(ProductType.MANUAL_ENTRY.getCode()); // 产品类型
                supplierOrderSystemCommodityAddReq.setSaleNumber(orderCommodity.getOrderId().toString()); // 销售单号
                supplierOrderSystemCommodityAddReq.setProductName(orderCommodity.getCommodityName()); // 产品名称
                supplierOrderSystemCommodityAddReq.setTotalFee(orderCommodity.getCommodityTotalPrice()); // 总金额
                supplierOrderSystemCommodityAddReq.setCurrency(Currency.HKD.getCurrency()); // 币种名称
                supplierOrderSystemCommodityAddReq.setCurrencyId(Currency.HKD.getCode()); // 币种id

                // 设置商品信息详情列表
                List<SupplierSystemOrderCommodityAddReq> supplierSystemOrderCommodityAddReqList = new ArrayList<>();
                SupplierSystemOrderCommodityAddReq addReq = new SupplierSystemOrderCommodityAddReq();
                // 订单id
                addReq.setOrderId(order.getId());
                // 客户备注
                addReq.setCustomerRemark(null);
                // 适合人群
                addReq.setSuitablePeople(null);
                // 供应商备注
                addReq.setSupplierRemark(null);

                // 商品信息详情列表
                List<SupplierSystemOrderCommodityDetailAddReq> reqList = new ArrayList<>();
                SupplierSystemOrderCommodityDetailAddReq commodityDetailAddReq = new SupplierSystemOrderCommodityDetailAddReq();
                commodityDetailAddReq.setOrderId(order.getId()); // 订单id
                commodityDetailAddReq.setCommodityName(orderCommodity.getCommodityName()); // 商品名称
                commodityDetailAddReq.setCommodityNumber(orderCommodity.getCommodityNumber()); // 商品编码
                commodityDetailAddReq.setNumber(orderCommodity.getNumber()); // 商品数量
                commodityDetailAddReq.setPrice(orderCommodity.getCommodityPrice()); // 商品单价
                commodityDetailAddReq.setPassengerName(null); // TODO 用户姓名
                reqList.add(commodityDetailAddReq);
                addReq.setSupplierSystemOrderCommodityDetailAddReqList(reqList);
                supplierSystemOrderCommodityAddReqList.add(addReq);

                // 商品信息列表
                supplierOrderSystemCommodityAddReq.setSupplierSystemOrderCommodityAddReqList(supplierSystemOrderCommodityAddReqList);
                supplierOrderSystemCommodityAddReq.setPayableAmount(orderCommodity.getCommodityTotalPrice());

                // 商品详情
                SupplierSystemOrderCommodityDetailAddReq detailAddReq = new SupplierSystemOrderCommodityDetailAddReq();
                // 订单id
                detailAddReq.setOrderId(order.getId());
                // 商品编号
                detailAddReq.setCommodityNumber(orderCommodity.getCommodityNumber());
                // 商品名称
                detailAddReq.setCommodityName(orderCommodity.getCommodityName());
                // 数量
                detailAddReq.setNumber(orderCommodity.getNumber());
                // 商品单价
                detailAddReq.setPrice(orderCommodity.getCommodityPrice());

                // collectommodityMap.get(orderCommodity.getCommodityId()).getSupplierId()
                log.info("【中旅商城--APP订单支付--新增供应商预订】，入参为:{}", JSONObject.toJSONString(supplierOrderSystemCommodityAddReq));
                supplierOrderService.addSystemCommodity(supplierOrderSystemCommodityAddReq, saleMan.getId());
            }
            /****************************************供应商预订单 end********************************************************/

            /****************************************财务中心新增收款记录 start********************************************************/
            List<BillAddCollectionReq> billAddCollectionReqs = new ArrayList<>();
            for (OrderCommodityCollection commodityCollection : orderCommodityCollections) {
                // 新增收款认款req
                BillAddCollectionReq billAddCollectionReq = new BillAddCollectionReq();
                billAddCollectionReq.setBillNumber(commodityCollection.getCollectionNumber()); // 收款单号
                billAddCollectionReq.setBusinessType(SystemBusinessType.COMMODITY.getCode());// 业务类型
                billAddCollectionReq.setCollectionWayId(paymentMethod.getPayRefundMethodId()); // 收款方式ID
                billAddCollectionReq.setCollectionWayName(paymentMethod.getName());// 收款方式
                billAddCollectionReq.setCollectionTypeId(CollectionTypeIdCode.FULL.getCode());// 收款类型id 全款
                billAddCollectionReq.setCollectionTypeName(CollectionTypeIdCode.FULL.getMsg()); // 收款类型 全款
                billAddCollectionReq.setCollectionAmount(totalMoney);// 收款金额
                billAddCollectionReq.setCurrencyId(Currency.HKD.getCode());// 币种id
                billAddCollectionReq.setCurrencyName(Currency.HKD.getCurrency()); // 币种名称
                billAddCollectionReq.setExchangeRate(marketExchangeRate.doubleValue());// 汇率
                billAddCollectionReq.setCollectionTime(now);// 收款时间
//        String collectionCertificateJson = req.getOrderCommodityPayDetailReqList().get(0).getCollectionCertificateJson();
                List<FileJson> fileJsons = JSON.parseArray(commodityCollection.getCollectionCertificateJson(), FileJson.class);
                billAddCollectionReq.setCollectionVoucherJsonList(fileJsons);// 收款凭证json
                billAddCollectionReq.setSaleOrderNumber(order.getOrderNumber());//订单号
                billAddCollectionReq.setSaleOrderId(order.getId());//订单id
                List<String> resourceInfo = new ArrayList<>();
                List<Long> commodityIds = new ArrayList<>();
                for (OrderCommodity orderCommodity : orderCommodities) {
                    commodityIds.add(orderCommodity.getCommodityId());
                    resourceInfo.add(orderCommodity.getCommodityName());
                }
                billAddCollectionReq.setProductId(commodityIds);//产品id列表 商品id
                billAddCollectionReq.setResourceInfo(resourceInfo);// 资源信息列表 --- 商品名称?
//                billAddCollectionReq.setProductNumber(commodityDTOList.get(0).getCommodityName()); // 产品编号/团号 商品名称
//                billAddCollectionReq.setProductName(commodityDTOList.get(0).getCommodityNumber());//产品编号、团号 商品编号
                billAddCollectionReq.setSaleUserId(saleMan.getId());// 销售人员id
                billAddCollectionReq.setSaleUserName(saleMan.getEnName());// 销售人员名称
                billAddCollectionReq.setSaleDeptId(saleMan.getDeptId());//销售部门id
                billAddCollectionReq.setUserId(saleMan.getId());// 用户id（当前用户）
                billAddCollectionReqs.add(billAddCollectionReq);
            }
            log.info("【中旅商城--APP订单支付--新增财务中心收款记录】，入参为:{}", JSONObject.toJSONString(billAddCollectionReqs));
            iFinanceBillService.addCollection(billAddCollectionReqs);
            /****************************************财务中心新增收款记录 end********************************************************/

            /*********更新订单状态start*********/
            order.setOrderStatus(2);
            order.setPaymentStatus(2);
            order.setCancelStatus(0);
            order.setScheduledStatus(1);
            log.info("【中旅商城】支付成功，修改订单几个状态，入参为:{}", JSONObject.toJSONString(order));
            orderMapper.updateOrderById(order);
            /*********更新订单状态end*********/
        } catch (BusinessException e) {
            log.error("【中旅商城APP-回调支付】唤起支付失败失败,error:{}", e.getMessage(), e);
            throw e;
        } catch (Exception e) {
            log.error("【中旅商城APP-回调支付】系统异常,error:{}", e.getMessage(), e);
            throw e;
        }
        return Result.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cancelAppOrder(List<OrderCommodityRefundReq> refundReqs, TokenUser tokenUser) {
        log.info("【中旅商城--取消订单--start】，入参为 -- refundReqs:{},user:{}", JSON.toJSONString(refundReqs), JSON.toJSONString(tokenUser));
        if ((null == refundReqs || refundReqs.size() == 0) || null == refundReqs.get(0).getOrderId()) {
            throw new BusinessException(SystemError.SYS_402);
        }
        Order order = orderMapper.selectById(refundReqs.get(0).getOrderId());
        if (order == null) {
            //订单不存在
            throw new BusinessException(SystemError.AIREXPRESS_ORDER_60002);
        }

        LocalDateTime now = LocalDateTime.now();
        // 订单状态:1：待付款; 2：待发货; 3：待收货; 4：已完成; 5：已取消
        // 付款状态:1：待支付;2：已付款
        if ((refundReqs.get(0).getPaymentStatus() == order.getPaymentStatus() && order.getPaymentStatus() == 1) &&
                (refundReqs.get(0).getOrderStatus() == order.getOrderStatus() && order.getOrderStatus() == 1)) {
            order.setOrderStatus(5);
            order.setModifiedId(tokenUser.getId());
            order.setGmtModified(now);
            orderMapper.updateById(order);
            return;
        }

        // 订单状态:1：待付款; 2：待发货; 3：待收货; 4：已完成; 5：已取消
        // 付款状态:1：待支付;2：已付款
        List<OrderCommodityRefund> orderCommodityRefundList = new ArrayList<>();
        BigDecimal amountCountHKD = BigDecimal.ZERO;//订单金额(港币)=实收金额+积分抵扣+优惠券
        BigDecimal refundAmount = BigDecimal.ZERO;
        for (OrderCommodityRefundReq commodityRefundReq : refundReqs) {
            BigDecimal amountHKD;
            if ((commodityRefundReq.getPaymentStatus() == order.getPaymentStatus() && order.getPaymentStatus() == 2)
                    && order.getOrderStatus() > 1) {
                OrderCommodityRefund orderCommodityRefund = new OrderCommodityRefund();
                BeanUtils.copyProperties(commodityRefundReq, orderCommodityRefund);
                // 获取对应汇率，计算支付金额
                MainDataCurrencyQueryDTO currencyQueryDTO = getExchangeRateByName(commodityRefundReq.getCurrencyId());
                BigDecimal marketExchangeRate = currencyQueryDTO.getMarketExchangeRate();
                amountHKD = commodityRefundReq.getRefundAmount().multiply(marketExchangeRate);
                amountCountHKD = amountCountHKD.add(amountHKD);
                refundAmount = refundAmount.add(orderCommodityRefund.getRefundAmount());
                orderCommodityRefund.setStatus(1); // 状态:(1：审批中 2：审批通过 3：审批不通过 4：退款成功)
                // 退款单号
                orderCommodityRefund.setRefundNumber(generateRefundNumberRule(now));
                // 本位币金额
                orderCommodityRefund.setStandardAmount(amountHKD);
                orderCommodityRefund.setGmtCreate(now);
                // 退款原因
                orderCommodityRefund.setRefundReason(refundReqs.get(0).getRefundReason());
                orderCommodityRefund.setCreateId(tokenUser.getId());
                orderCommodityRefund.setGmtModified(now);
                orderCommodityRefund.setModifiedId(tokenUser.getId());
                orderCommodityRefund.setIsDeleted(IsDeletedCode.NO.getCode());
                log.info("【中旅商城--取消订单--退款记录】，入参为:{}", JSON.toJSONString(orderCommodityRefund));
                orderCommodityRefundMapper.insert(orderCommodityRefund);
            }
        }
//        createApproval(order, tokenUser); // 创建一个退款审批流程
        if (order.getPaymentStatus().intValue() == PayOrderStatus.FULFIL.getStatus()) {
            checkAmount(amountCountHKD, order.getOrderAmount());
        }
        updateStatusToAppUser(order.getId());
        log.info("【中旅商城--取消订单--end】");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cancelOrder(OrderCommodityRefundReq2 refundReq, TokenUser tokenUser) {
        log.info("【中旅商城B端--取消订单--start】，入参为 -- refundReqs:{},tokenUser:{}", JSON.toJSONString(refundReq), JSON.toJSONString(tokenUser));
        if (null == refundReq || null == refundReq.getOrderId()) {
            throw new BusinessException(SystemError.SYS_402);
        }
        Order order = orderMapper.selectOrderById(refundReq.getOrderId());
        log.info("【中旅商城B端--取消订单--查询订单】，返参为：{}", JSON.toJSONString(order));
        if (order == null) {
            //订单不存在
            throw new BusinessException(SystemError.AIREXPRESS_ORDER_60002);
        }

        LocalDateTime now = LocalDateTime.now();
        // 订单状态:1：待付款; 2：待发货; 3：待收货; 4：已完成; 5：已取消
        // 付款状态:1：待支付;2：已付款
        if ((refundReq.getPaymentStatus() == order.getPaymentStatus() && order.getPaymentStatus() == 1) &&
                (refundReq.getOrderStatus() == order.getOrderStatus() && order.getOrderStatus() == 1)) {
            order.setOrderStatus(5);
            order.setModifiedId(tokenUser.getId());
            order.setGmtModified(now);
            orderMapper.updateById(order);
            return;
        }

        BigDecimal amountCountHKD = BigDecimal.ZERO;//订单金额(港币)=实收金额+积分抵扣+优惠券
        BigDecimal refundAmount = BigDecimal.ZERO;
        BigDecimal amountHKD;
        // 订单状态:1：待付款; 2：待发货; 3：待收货; 4：已完成; 5：已取消
        // 付款状态:1：待支付;2：已付款
        if ((refundReq.getPaymentStatus() == order.getPaymentStatus() && order.getPaymentStatus() == 2)
                && order.getOrderStatus() > 1) {
            List<OrderCommodityRefundCancelReq> orderCommodityRefundCancelReqList = refundReq.getOrderCommodityRefundCancelReqList();
            if (orderCommodityRefundCancelReqList != null && orderCommodityRefundCancelReqList.size() > 0) {

                for (OrderCommodityRefundCancelReq orderCommodityRefundCancelReq : orderCommodityRefundCancelReqList) {
                    long id = SnowflakeIdWorker.nextId();
                    // 添加退款审批记录给对应的账号
                    OrderCommodityRefund orderCommodityRefund = new OrderCommodityRefund();
                    // 订单id
                    orderCommodityRefund.setOrderId(refundReq.getOrderId());
                    // 收款币种id
                    orderCommodityRefund.setCurrencyId(orderCommodityRefundCancelReq.getCurrencyId());
                    // 兑换率
                    orderCommodityRefund.setExchangeRate(orderCommodityRefundCancelReq.getExchangeRate());
                    // 收款币种
                    orderCommodityRefund.setCurrency(Currency.HKD.getCurrency());
                    // 本位币金额（HKD）
                    orderCommodityRefund.setStandardAmount(amountCountHKD);
                    // 退款单号
                    orderCommodityRefund.setRefundNumber(getRefundNumber());
                    // 退款金额
                    orderCommodityRefund.setRefundAmount(amountCountHKD);
                    // 退款方式id
                    orderCommodityRefund.setRefundWayId(orderCommodityRefundCancelReq.getRefundWayId());
                    // 退款方式
                    orderCommodityRefund.setRefundWay(orderCommodityRefundCancelReq.getRefundWay());
                    // 退款账户
                    orderCommodityRefund.setRefundAccount(orderCommodityRefundCancelReq.getRefundAccount());
                    // 退款原因
                    orderCommodityRefund.setRefundReason(refundReq.getRefundReason());
                    // 备注
                    orderCommodityRefund.setRemark(refundReq.getRemark());
                    // 状态:(1：审批中 2：审批通过 3：审批不通过 4：退款成功)
                    orderCommodityRefund.setStatus(1);
                    // 拒绝原因
                    orderCommodityRefund.setRejectReason(refundReq.getRefundReason());
                    // 创建人
                    orderCommodityRefund.setCreateId(tokenUser.getId());
                    // 修改人
                    orderCommodityRefund.setModifiedId(tokenUser.getId());
                    // 删除标识
                    orderCommodityRefund.setIsDeleted(0);
                    // 退款id
                    orderCommodityRefund.setId(id);
                    // 创建时间
                    orderCommodityRefund.setGmtCreate(LocalDateTime.now());
                    // 修改时间
                    orderCommodityRefund.setGmtModified(LocalDateTime.now());
//                    orderCommodityRefund.setId(SnowflakeIdWorker.nextId());
                    BeanUtils.copyProperties(refundReq, orderCommodityRefund);
                    // 获取对应汇率，计算支付金额
                    MainDataCurrencyQueryDTO currencyQueryDTO = getExchangeRateByName(orderCommodityRefundCancelReq.getCurrencyId());
                    BigDecimal marketExchangeRate = currencyQueryDTO.getMarketExchangeRate();
                    amountHKD = orderCommodityRefundCancelReq.getRefundAmount().multiply(marketExchangeRate);
                    amountCountHKD = amountCountHKD.add(amountHKD);
                    refundAmount = refundAmount.add(orderCommodityRefund.getRefundAmount());
                    // 状态:(1：审批中 2：审批通过 3：审批不通过 4：退款成功)
                    orderCommodityRefund.setStatus(1);
                    orderCommodityRefund.setRefundNumber(generateRefundNumberRule(now));
                    orderCommodityRefund.setStandardAmount(amountHKD);
                    orderCommodityRefund.setGmtCreate(now);
                    orderCommodityRefund.setCreateId(tokenUser.getId());
                    orderCommodityRefund.setGmtModified(now);
                    orderCommodityRefund.setModifiedId(tokenUser.getId());
                    orderCommodityRefund.setIsDeleted(IsDeletedCode.NO.getCode());
                    orderCommodityRefundMapper.insertRefund(orderCommodityRefund);
                }
            }
        }
        // 已支付取消才進行應收實收金額判斷
        if (order.getPaymentStatus().intValue() == PayOrderStatus.FULFIL.getStatus()) {
            checkAmount(order.getOrderAmount(), amountCountHKD);
        }
        createApproval(order, tokenUser); // 创建一个退款审批流程
    }

    /**
     * 获取订单退款单号
     * 规则 TKD+年後2位+月日4位+時分秒6位+2位隨機數字/小寫字母
     *
     * @return String
     */
    public static String getRefundNumber() {
        StringBuffer refund = new StringBuffer();
        refund.append("TKD");
        String year = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yy"));
        refund.append(year);
        String month = LocalDateTime.now().format(DateTimeFormatter.ofPattern("MMdd"));
        refund.append(month);
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HHmmss"));
        refund.append(time);
        Random random = new Random();
        int number = random.nextInt(90) + 10;
        refund.append(number + "");
        return refund.toString();
    }

    /**
     * 创建一个退款审批流程
     *
     * @param order     订单对象
     * @param tokenUser 用户对象
     */
    private void createApproval(Order order, TokenUser tokenUser) {
        // todo 创建一个审批流程
        long approvalTypeId = SysApprovalType.CANCEL_COMMODITY.getCode(); // 取消订单审批
        try {
            Result<ApprovalStartDTO> result = sysApprovalService.start(SystemBusinessType.COMMODITY.getCode(), approvalTypeId, order.getId(), tokenUser.getId(), null, null);
            if (result.isSuccess()) {
                order.setApprovalId(result.getData().getApprovalId());
                order.setCancelStatus(GoodsApprovalStatusConstants.UNDER_APPROVAL.getCode()); // 审批状态：1：待提交；2：审批中；3：s审批通过；4：审批未通过
                orderMapper.updateById(order);
            } else {
                throw new BusinessException(SystemError.MALL_MERCHANDISE_23013);
            }
        } catch (Exception e) {
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23014);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void remarkOrder(OrderAddReq addReq, Long userId) {
        if (null == addReq || null == addReq.getId() || (StringUtils.isBlank(addReq.getOrderNotes()))) {
            throw new BusinessException(SystemError.SYS_402);
        }
        Order order = orderMapper.selectById(addReq.getId());
        order.setModifiedId(userId);
        order.setGmtModified(LocalDateTime.now());
        order.setOrderNotes(addReq.getOrderNotes());
        orderMapper.updateById(order);
    }

    /**
     * 校验支付金额是否小于应收金额
     *
     * @param amountCountHKD   支付金额
     * @param receivableAmount 应收价格
     */
    private void checkAmount(BigDecimal amountCountHKD, BigDecimal receivableAmount) {
        if (amountCountHKD.compareTo(receivableAmount) < 0) {
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23041);
        }
    }

    /**
     * 生成收款单号:
     * SKD+年後2位+月日4位+時分秒6位+2位隨機數字
     */
    private String generatorPaymentNumber(LocalDateTime nowLocalDateTime) {
        String yearCode = String.valueOf(nowLocalDateTime.getYear()).substring(2, 4);
        String monthCode = StringUtils.leftPad(String.valueOf(nowLocalDateTime.getMonthValue()), 2, "0");
        String dayCode = StringUtils.leftPad(String.valueOf(nowLocalDateTime.getDayOfMonth()), 2, "0");
        String hourCode = StringUtils.leftPad(String.valueOf(nowLocalDateTime.getHour()), 2, "0");
        String minuteCode = StringUtils.leftPad(String.valueOf(nowLocalDateTime.getMinute()), 2, "0");
        String secondCode = StringUtils.leftPad(String.valueOf(nowLocalDateTime.getSecond()), 2, "0");
        String randomNumber = String.valueOf((int) ((Math.random() * 9 + 1) * 10));
        StringBuilder orderNumberSb = new StringBuilder();
        orderNumberSb.append("SKD").append(yearCode).append(monthCode).append(dayCode).append(hourCode)
                .append(minuteCode).append(secondCode).append(randomNumber);
        return orderNumberSb.toString().toUpperCase();
    }

    /**
     * 获取银联优惠金额
     *
     * @param order
     * @param orderCommodityCollection
     * @param user
     * @return
     */
    private void useAmountByBankReference(Order order, OrderCommodityCollection
            orderCommodityCollection, UserDTO user) {
        OperateBankConformQueryReq operateBankConformQueryReq = new OperateBankConformQueryReq();
        operateBankConformQueryReq.setId(orderCommodityCollection.getUnionpayDiscountId());//银联优惠ID
        operateBankConformQueryReq.setCardNumber(orderCommodityCollection.getPayer());//卡号
        operateBankConformQueryReq.setTotalPaidIn(order.getOrderAmount());//订单金额
        operateBankConformQueryReq.setBusinessType(SystemBusinessType.COMMODITY.getCode()); //业务类型
        operateBankConformQueryReq.setRelationId(order.getId());//订单ID
        operateBankConformQueryReq.setChannelId(OrderSource.PC_NET.getCode().longValue());//订单来源
        operateBankConformQueryReq.setUserId(user.getId());// 用户id
//        operateBankConformQueryReq.setDiscountObjectId();//会员类型
        Result<OperateBankPreferenceQueryDTO> operateBankPreferenceQueryDTOResult = operateBankPreferenceService.queryConform(operateBankConformQueryReq);
        if (!operateBankPreferenceQueryDTOResult.isSuccess()) {
            // 校验银行优惠不满足条件
            SystemError defined = SystemError.getDefined(operateBankPreferenceQueryDTOResult.getCode());
            throw new BusinessException(defined);
        }
        OperateBankPreferenceQueryDTO bankQueryDto = operateBankPreferenceQueryDTOResult.getData();
        if (bankQueryDto.getDiscountType() == 1) {
            // 使用满额折扣优惠
            // 校验应收价格是否符合满减优惠
            if (order.getOrderAmount().compareTo(bankQueryDto.getFullAmount()) == -1) {
                // 校验银行优惠不满足条件
                throw new BusinessException(SystemError.AIREXPRESS_ORDER_60018);
            }
            orderCommodityCollection.setCollectionAmount(bankQueryDto.getReductionAmount());
        } else {
            // 使用百分比优惠
            BigDecimal currentAmount = order.getOrderAmount().multiply(new BigDecimal(String.valueOf(bankQueryDto.getDiscountPercent())));
            currentAmount = currentAmount.compareTo(bankQueryDto.getMaxDiscount()) > 0 ? bankQueryDto.getMaxDiscount() : currentAmount;
            orderCommodityCollection.setCollectionAmount(currentAmount);
        }
        /**
         * 扣减银联优惠
         */
        OperateBankDeductReq deductReq = new OperateBankDeductReq();
        deductReq.setId(orderCommodityCollection.getUnionpayDiscountId());//银联优惠ID
        deductReq.setCardNumber(orderCommodityCollection.getPayer());//卡号
        deductReq.setTotalPaidIn(order.getOrderAmount());//订单金额
        deductReq.setBusinessType(SystemBusinessType.COMMODITY.getCode()); // 业务类型
        deductReq.setRelationId(order.getId());//订单ID
        deductReq.setChannelId(OrderSource.PC_NET.getCode().longValue());//订单来源
        TokenUser tokenUser = new TokenUser();
        tokenUser.setId(user.getId());
        // 扣减银联优惠剩余名额及剩余金额
        Result deductResult = operateBankPreferenceService.deduct(deductReq, tokenUser);
        if (!deductResult.isSuccess()) {
            // 校验银行优惠不满足条件
            SystemError defined = SystemError.getDefined(deductResult.getCode());
            throw new BusinessException(defined);
        }
    }

    /**
     * 根据币种ID获取汇率，获取汇率,
     *
     * @return
     */
    private MainDataCurrencyQueryDTO getExchangeRateByName(Long currencyId) {
        MainDataCurrencyUpdateStatusReq mainDataCurrencyUpdateStatusReq = new MainDataCurrencyUpdateStatusReq();
        mainDataCurrencyUpdateStatusReq.setId(currencyId);
        Result<MainDataCurrencyQueryDTO> queryCurrencyRateResult = mainDataCurrencyService.query(mainDataCurrencyUpdateStatusReq);
        log.info("【查询汇率】exchange rate:{}", JSON.toJSONString(queryCurrencyRateResult));
        if (!queryCurrencyRateResult.isSuccess()) {
            SystemError defined = SystemError.getDefined(queryCurrencyRateResult.getCode());
            throw new BusinessException(defined);
        }
        return queryCurrencyRateResult.getData();
    }

    /**
     * 校驗訂單入參基本參數
     *
     * @param addReq 訂單入參
     * @throws Exception 異常
     */
    private void checkAddOrderParam(OrderAddReq addReq) throws Exception {
        if (null == addReq || null == addReq.getDeliveryMode()) {
            throw new BusinessException(SystemError.SYS_402);
        }
        if (addReq.getDeliveryMode().intValue() == 1) {
            OrderConsigneeInfoReq orderConsigneeInfoReq = addReq.getOrderConsigneeInfoReq();
            if (orderConsigneeInfoReq == null) {
                throw new BusinessException(SystemError.SYS_402);
            }

        } else if (addReq.getDeliveryMode().intValue() == 2) {
            OrderShipperInfoReq orderShipperInfoReq = addReq.getOrderShipperInfoReq();
            if (orderShipperInfoReq == null) {
                throw new BusinessException(SystemError.SYS_402);
            }
        }
        if (CollectionUtils.isEmpty(addReq.getOrderCommodityReqList())) {
            throw new BusinessException(SystemError.SYS_402);
        }
    }

    @Override
    public PageResponse<OrderPageListDTO> orderPageList(OrderPageListReq req, TokenUser tokenUser) {
        if (null == req) {
            throw new BusinessException(SystemError.SYS_402);
        }
        if (null == tokenUser.getId()) {
            throw new BusinessException(SystemError.SYS_406);
        }

        Result<List<Long>> permissionResult = sysPermissionService.queryPermission(req.getMenuId(), tokenUser.getId());
        if (!permissionResult.isSuccess()) {
            SystemError result = SystemError.getDefined(permissionResult.getCode());
            throw new BusinessException(result);
        }
        //不是管理员
        if (!GlobalConstants.Role.isAdmin(tokenUser.getUsername())) {
            req.setIsNotAdmin(1);
            String ids = "";
            List<Long> data = permissionResult.getData();
            if (data != null && data.size() > 0) {
                for (Long datum : data) {
                    ids += datum + ",";
                }
            }
            if (ids.length() > 0) {
                ids = ids.substring(0, ids.length() - 1);
            }
            req.setUserIds(ids);
        }

        IPage<OrderPageListDTO> page = new Page<OrderPageListDTO>(req.getPageNo(), req.getPageSize());
        IPage<OrderPageListDTO> iPage = orderMapper.findOrderPageByCondition(page, req);
        List<OrderPageListDTO> recordsList = iPage.getRecords();
        getCommodityDetails(recordsList);
        List<OrderPageListDTO> pageDTOList = EntityUtil.copyList(recordsList, OrderPageListDTO.class);
        return new PageResponse<>(pageDTOList, iPage.getCurrent() == 1,
                iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()),
                iPage.getTotal(), iPage.getCurrent(), iPage.getSize());

    }

    @Override
    public OrderDetailDTO getOrderDetailed(Long orderId, Integer type, TokenUser tokeneUsr) {
        // 参数判断
        if (orderId == null || type == null) {
            throw new BusinessException(SystemError.SYS_402);
        }
        if (tokeneUsr == null) {
            throw new BusinessException(SystemError.SYS_406);
        }

        // 订单id查询提货人收货人信息
        OrderDetailDTO dbOrderDetailDTO = orderMapper.findOrderCustomerInfoByOrderId(orderId);
        if (dbOrderDetailDTO == null) {
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23000);
        }

        // 订单id查询商品信息
        List<OrderCommodityPageListDetailDTO> dbOrderCommodityList = orderCommodityMapper.findCommodityDetailsByOrderId(Arrays.asList(orderId));
        if (type == 0) {
            // 订单id查询商品订单收款明细
            List<OrderCommodityCollectionDTO> dbCommodityCollectionList = orderCommodityCollectionMapper.findOrderCommodityCollectionByOrderId(orderId);
            // 订单id查询商品订单退款记录
            List<OrderCommodityRefundDTO> dbCommodityRefundList = orderCommodityRefundMapper.findOrderCommodityRefundByOrderId(orderId);

            // 返回DTO收款明细
            dbOrderDetailDTO.setOrderCommodityCollectionDTOList(dbCommodityCollectionList);
            // 返回DTO退款明细
            dbOrderDetailDTO.setOrderCommodityRefundDTOList(dbCommodityRefundList);
        }

        // 返回DTO订单明细
        dbOrderDetailDTO.setOrderCommodityPageListDetailDTOList(dbOrderCommodityList);
        return dbOrderDetailDTO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateOrderConsigneeInfo(OrderConsigneeInfoReq orderConsigneeInfoReq, TokenUser tokenUser) {
        if (tokenUser == null) {
            throw new BusinessException(SystemError.SYS_406);
        }
        if (orderConsigneeInfoReq == null || orderConsigneeInfoReq.getOrderId() == null) {
            throw new BusinessException(SystemError.SYS_402);
        }
        OrderConsigneeInfo orderConsigneeInfo = orderConsigneeInfoMapper.findConsigneeInfoByOrder(orderConsigneeInfoReq.getOrderId());
        BeanUtils.copyProperties(orderConsigneeInfoReq, orderConsigneeInfo, EntityUtil.getNullPropertyNames(orderConsigneeInfoReq));
        orderConsigneeInfo.setGmtModified(LocalDateTime.now());
        orderConsigneeInfo.setModifiedId(tokenUser.getId());
        orderConsigneeInfoMapper.updateById(orderConsigneeInfo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void upOrderCommodityDeliverGoods(OrderCommodityDeliverGoodsReq req, TokenUser tokenUser) {
        if (req == null) {
            throw new BusinessException(SystemError.SYS_402);
        }
        if (tokenUser == null) {
            throw new BusinessException(SystemError.SYS_406);
        }
        LocalDateTime now = LocalDateTime.now();
        List<Long> ids = req.getIds();
        List<OrderCommodity> orderCommodities = orderCommodityMapper.selectBatchIds(ids);
        orderCommodities.stream().forEach(orderCommoditie -> {
            orderCommoditie.setLogisticsCompanyId(req.getLogisticsCompanyId());
            orderCommoditie.setLogisticsCompanyName(req.getLogisticsCompanyName());
            orderCommoditie.setLogisticsOrderNo(req.getLogisticsOrderNo());
            orderCommoditie.setLogisticsCompanyPhone(req.getLogisticsCompanyPhone());
            orderCommoditie.setGmtModified(now);
            orderCommoditie.setModifiedId(tokenUser.getId());
            orderCommodityMapper.updateById(orderCommoditie);
        });
        if (StringUtils.isNotBlank(req.getIsAllCommodity())) { // 訂單下所有商品全部發貨后，狀態更新為待收貨。
            if ("Y".equalsIgnoreCase(req.getIsAllCommodity())) {
                Order order = orderMapper.selectById(req.getOrderId());
                order.setOrderStatus(3); // 3-待收貨
                order.setGmtModified(now);
                order.setModifiedId(tokenUser.getId());
                orderMapper.updateById(order);
            }
        }
    }

    @Override
    public void cancelOrderApprovalProcess(OrderCancelApprovalProcessReq orderCancelApprovalProcessReq, TokenUser tokenUser) {
        if (orderCancelApprovalProcessReq == null || null == orderCancelApprovalProcessReq.getOrderId()) {
            throw new BusinessException(SystemError.SYS_402);
        }
        if (tokenUser == null) {
            throw new BusinessException(SystemError.SYS_406);
        }
        log.info("cancelOrderApprovalProcess params:{}", JSONArray.toJSON(orderCancelApprovalProcessReq).toString());
        if (Arrays.asList("3", "4").contains(orderCancelApprovalProcessReq.getToApprovalStatus().toString())) {
            LocalDateTime now = LocalDateTime.now();
            Order order = orderMapper.selectById(orderCancelApprovalProcessReq.getOrderId());
            Result<ApprovalCheckDTO> result = sysApprovalService.check(order.getApprovalId(), tokenUser.getId(), orderCancelApprovalProcessReq.getToApprovalStatus(), orderCancelApprovalProcessReq.getComments() == null ? "" : orderCancelApprovalProcessReq.getComments());
            if (!result.isSuccess()) {
                SystemError error = SystemError.getDefined(result.getCode());
                throw new BusinessException(error);
            }
            if (result.getData().getIsFinish()) {
                order.setCancelStatus(orderCancelApprovalProcessReq.getToApprovalStatus());
                order.setModifiedId(tokenUser.getId());
                order.setGmtModified(now);
                baseMapper.updateById(order);
                List<OrderCommodityRefundDTO> dbOrderCommodityRefund = orderCommodityRefundMapper.findOrderCommodityRefundByOrderId(order.getId());
                dbOrderCommodityRefund.forEach(p -> {
                    OrderCommodityRefund orderCommodityRefund = new OrderCommodityRefund();
                    BeanUtils.copyProperties(p, orderCommodityRefund);
                    // 状态:(1：审批中 2：审批通过 3：审批不通过 4：退款成功)
                    orderCommodityRefund.setStatus(orderCancelApprovalProcessReq.getToApprovalStatus() == 3 ? 2 : 3);
                    orderCommodityRefund.setRejectReason(orderCancelApprovalProcessReq.getComments());
                    orderCommodityRefundMapper.updateById(orderCommodityRefund);
                });
            }
        }
    }

    @Override
    public void deleteApprovalRejected(Long id, TokenUser tokenUser) {
        if (tokenUser == null) {
            throw new BusinessException(SystemError.SYS_406);
        }
        if (id == null) {
            throw new BusinessException(SystemError.SYS_402);
        }
        orderCommodityRefundMapper.deleteById(id);
    }

    @Override
    public Result updateRefundStatus(Long id, TokenUser tokenUser) {
        log.info("【中旅商城B端--操作退款--确认退款更新状态--start】，入参为 -- tokenUser:{},id:{}", JSON.toJSONString(tokenUser), id);
        if (tokenUser == null) {
            throw new BusinessException(SystemError.SYS_406);
        }
        if (id == null) {
            throw new BusinessException(SystemError.SYS_402);
        }

        log.info("【中旅商城--操作退款--查询订单】，入参为：{}", id);
        Order order = orderMapper.selectOrderById(id);
        log.info("【中旅商城--操作退款--查询订单】，返参为：{}", JSON.toJSONString(order));
        if (null == order) {
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23033);
        }
        log.info("【中旅商城--操作退款--查询商品退款记录】，入参为：{}", id);
        OrderCommodityRefund orderCommodityRefund = orderCommodityRefundMapper.selectByOrderId(id);
        log.info("【中旅商城B端--操作退款--查询商品退款记录】，返参为:{}", JSON.toJSONString(orderCommodityRefund));
        if (null != orderCommodityRefund && orderCommodityRefund.getStatus() == 3) {
            orderCommodityRefund.setStatus(4); // 4：退款成功
            orderCommodityRefund.setModifiedId(tokenUser.getId());
            orderCommodityRefund.setGmtModified(LocalDateTime.now());
            orderCommodityRefundMapper.updateById(orderCommodityRefund);
        } else {
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23028);
        }

        /**
         * 退款确认--回滚挂账额度
         */
        RollBackQuotaReq rollBackQuotaReq = new RollBackQuotaReq();
        // 订单id
        rollBackQuotaReq.setOrderId(orderCommodityRefund.getOrderId());
        // 收款单号
//        rollBackQuotaReq.setCollectionNumber("");
        // 退款单号
        rollBackQuotaReq.setRefundNumber(orderCommodityRefund.getRefundNumber());
        // 退款金额
        rollBackQuotaReq.setAmount(orderCommodityRefund.getRefundAmount());
        // 业务类型
        rollBackQuotaReq.setBusinessType(SystemBusinessType.COMMODITY.getCode());
        // 当前用户
        rollBackQuotaReq.setUserId(tokenUser.getId());
        log.info("【中旅商城B端--操作退款--回滚挂账额度】，入参为:{}", JSON.toJSONString(rollBackQuotaReq));
        onAccountCurrencyQuotaService.rollBackQuota(rollBackQuotaReq);
        log.info("【中旅商城B端--操作退款--end】");
        return Result.success();
    }

    @Override
    public List<OrderCommodityPageListDetailDTO> salesVolume() {
        return orderMapper.salesVolume();
    }

    @Override
    public Result<List<MyOrderDetailDTO>> recentToNow(LocalDateTime recent, LocalDateTime now) {
        List<Order> orderList = baseMapper.selectList(Wrappers.<Order>lambdaQuery()
                .eq(Order::getIsDeleted, IsDeletedCode.NO.getCode())
                .ge(recent != null, Order::getGmtModified, recent)
                .le(Order::getGmtModified, now));

        List<MyOrderDetailDTO> result = new ArrayList<>();
        for (Order order : orderList) {
            MyOrderDetailDTO orderDetailDTO = EntityUtil.copy(order, MyOrderDetailDTO.class);
            List<OrderCommodityPageListDetailDTO> commodityDetailsByOrderId = orderCommodityMapper.findCommodityDetailsByOrderId(Lists.newArrayList(orderDetailDTO.getId()));
            orderDetailDTO.setOrderCommodityPageListDetailDTOList(commodityDetailsByOrderId);
            result.add(orderDetailDTO);
        }
        return Result.success(result);
    }

    private void getCommodityDetails(List<OrderPageListDTO> recordsList) {
        List<Long> orderIds = recordsList.stream().map(p -> p.getId()).collect(Collectors.toList());
        List<OrderCommodityPageListDetailDTO> dbOrderCommodityList = orderCommodityMapper.findCommodityDetailsByOrderId(orderIds);
        if (dbOrderCommodityList == null) {
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23000);
        }
        Map<Long, List<OrderCommodityPageListDetailDTO>> orderCommodityGroup = dbOrderCommodityList.stream()
                .collect(Collectors.groupingBy(OrderCommodityPageListDetailDTO::getOrderId));
        for (OrderPageListDTO order : recordsList) {
            List<OrderCommodityPageListDetailDTO> orderCommoditys = orderCommodityGroup.get(order.getId());
            if (CollectionUtils.isEmpty(orderCommoditys) && null != order.getId()) {
//                throw new BusinessException(SystemError.MALL_MERCHANDISE_23000);
                continue;
            }
            order.setOrderCommodityPageListDetailDTOList(orderCommoditys);
        }
    }

    /**
     * 生成中旅商城销售编号=S+部门代码+员工编号+年后2位+月日4位+3位随机数字
     *
     * @param userDTO
     * @return
     */
    public static String generatorOrderNumber(UserDTO userDTO, LocalDateTime nowLocalDateTime) {
        String employeeNumber = userDTO.getEmployeeNumber();
        String deptCode = userDTO.getDeptCode();
        String date = DateUtil.fmt(nowLocalDateTime, "yyMMdd");
        String randomNumber = String.valueOf((int) ((Math.random() * 9 + 1) * 100));
        StringBuilder orderNumberSb = new StringBuilder();
        orderNumberSb.append("S").append(deptCode).append(employeeNumber).append(date).append(randomNumber);
        return orderNumberSb.toString().toUpperCase();
    }

    /**
     * 获取销售人并生成销售编号
     *
     * @param order
     * @param companyType
     */
    private UserDTO getSaleMan(Order order, String companyType, LocalDateTime now) {
        DispatchOrderRuleGetUserReq dispatchOrderRuleGetUserReq = new DispatchOrderRuleGetUserReq();
        dispatchOrderRuleGetUserReq.setBusinessTypeId(SystemBusinessType.COMMODITY.getCode());
        dispatchOrderRuleGetUserReq.setCompanyType(companyType);
        Result<Long> result = dispatchOrderRuleService.getDispatchUserId(dispatchOrderRuleGetUserReq);
        if (!result.isSuccess()) {
            log.error("【中旅商城APP-提交订单】获取销售人失败:{},msg:{}", result.getCode(), result.getMsg());
            throw new BusinessException(SystemError.getDefined(result.getCode()));
        }
        UserDTO saleUser = sysUserService.queryCacheUser(result.getData());
        String orderNumber = OrderServiceImpl.generatorOrderNumber(saleUser, now);
        order.setOrderNumber(orderNumber);
        return saleUser;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result payAppOrder(OrderCommodityPayReq req, String payMethod) {
        log.info("【中旅商城--APP支付订单--start】,入参为：{}", JSON.toJSONString(req));
        // 根据订单id查询订单
        Order order = orderMapper.selectOrderById(req.getId());
        if (Objects.isNull(order)) {
            return Result.failed(SystemError.MALL_MERCHANDISE_23033);
        }

        order.setPayMethod(payMethod);
        orderMapper.updateOrderById(order);

        // 订单金额
        BigDecimal orderAmount = order.getOrderAmount();
        // 获取订单收款明细
        List<OrderCommodityPayDetailReq> orderCommodityPayDetailReqs = req.getOrderCommodityPayDetailReqList();
        if (req.getIsUnionpayDiscount().intValue() == NumberConstant.ONE.getValue().intValue() &&
                (null == req.getUnionpayDiscountId() || req.getUnionpayDiscountId().intValue() < NumberConstant.ONE.getValue().intValue())) {
            return Result.failed(SystemError.MALL_MERCHANDISE_23034);
        }
        // 市场交换汇率
        BigDecimal marketExchangeRate = null;
        // 总金额
        BigDecimal totalMoney = BigDecimal.ZERO;

        // 订单收款明细
        List<OrderCommodityCollection> orderCommodityCollections = Lists.newArrayList();

        LocalDateTime now = LocalDateTime.now();
        log.info("【中旅商城--APP支付接口--获取销售人】，入参为：order:{},code:{},now:{}", JSON.toJSONString(order), CompanyType.HK_CT.getCode(), now);
        // 随机获取销售人
        UserDTO saleMan = getSaleMan(order, CompanyType.HK_CT.getCode(), now);
        log.info("【中旅商城--APP支付接口--获取销售人】，返参为：UserDTO:{}", JSON.toJSONString(saleMan));

        log.info("【中旅商城--APP支付接口--支付详情】，入参为：{}", JSON.toJSONString(orderCommodityPayDetailReqs));
        for (OrderCommodityPayDetailReq orderCommodityPayDetailReq : orderCommodityPayDetailReqs) {
            OrderCommodityCollection orderCommodityCollection = EntityUtil.copy(orderCommodityPayDetailReq, OrderCommodityCollection.class);
            // 生成收款单号
            String paymentNumber = generatorPaymentNumber(now);
            orderCommodityCollection.setCollectionNumber(paymentNumber);
            // 是否使用pos机（1、是 0、否）
            orderCommodityCollection.setIsPos(req.getIsPos());
            // 是否银联优惠
            orderCommodityCollection.setIsUnionpayDiscount(req.getIsUnionpayDiscount());
            // 银联优惠id
            orderCommodityCollection.setUnionpayDiscountId(req.getUnionpayDiscountId());
            // 支付方式id
            orderCommodityCollection.setCollectionWayId(orderCommodityPayDetailReq.getCollectionWayId());
            // 支付方式
            orderCommodityCollection.setCollectionWay(orderCommodityPayDetailReq.getCollectionWay());
            // 订单商品收款明细id
            orderCommodityCollection.setId(IdWorker.getId());
            // 订单id
            orderCommodityCollection.setOrderId(order.getId());
            // 创建人id
            orderCommodityCollection.setCreateId(saleMan.getId());
            // 更新人id
            orderCommodityCollection.setModifiedId(saleMan.getId());
            if (null != saleMan) {
                // 销售人员id
                orderCommodityCollection.setSalerId(saleMan.getId());
                // 销售人员名称
                orderCommodityCollection.setSalerName(saleMan.getUsername());
            }
            // 创建时间
            orderCommodityCollection.setGmtCreate(now);
            // 更新时间
            orderCommodityCollection.setGmtModified(now);
            // 删除标识 0 删除 1 未删除
            orderCommodityCollection.setIsDeleted(IsDeletedCode.NO.getCode());

            /******************************记录汇率 start*******************************/
            //获取汇率
            MainDataCurrencyQueryDTO exchangeRate = getExchangeRateByCurrencyId(orderCommodityPayDetailReq.getCurrencyId());
            //保证汇率存在
            if (exchangeRate == null || exchangeRate.getMarketExchangeRate() == null) {
                throw new BusinessException(SystemError.AIR_ORDER_15011, orderCommodityPayDetailReq.getCurrency());
            }
            marketExchangeRate = exchangeRate.getMarketExchangeRate();
            //当前汇率
            orderCommodityCollection.setExchangeRate(marketExchangeRate.doubleValue());
            //
            BigDecimal divide = orderCommodityPayDetailReq.getCollectionAmount().multiply(marketExchangeRate)
                    // 去掉小数点多余的3位数
                    .setScale(3, BigDecimal.ROUND_DOWN);

            // 数据库表无汇率值和汇率转换之后的金额字段，看需求是否需要增加字段
            //计算金额
            // orderCommodityCollection.setExchangeRateAfterMoney(divide);
            //汇率ID
            // orderCommodityCollection.setExchangeRateId(exchangeRate.getId());

            //累计金额
            totalMoney = totalMoney.add(divide);
            /*****************************记录汇率 end********************************/

            orderCommodityCollectionMapper.insertOrderCommodityCollection(orderCommodityCollection);
            orderCommodityCollections.add(orderCommodityCollection);
        }

        /****************************************供应商预订单 start********************************************************/
        //订单详情的金额需要<=实付金额
        if (order.getOrderAmount().compareTo(totalMoney) > 0) {
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23035);
        }

        // 查询订单商品信息
//        QueryWrapper<OrderCommodity> orderCommodityQueryWrapper = new QueryWrapper<>();
//        orderCommodityQueryWrapper.lambda().eq(OrderCommodity::getOrderId, req.getId());
//        List<OrderCommodity> orderCommodities = orderCommodityMapper.selectList(orderCommodityQueryWrapper);
        log.info("【中旅商城--APP订单支付--商品订单】，入参为：{}", JSON.toJSONString(req.getId()));
        List<OrderCommodity> orderCommodities = orderCommodityMapper.selectListByOrderId(req.getId());
        log.info("【中旅商城--APP订单支付--商品订单】，返参为：{}", JSON.toJSONString(orderCommodities));
        if (CollectionUtils.isEmpty(orderCommodities)) {
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23033);
        }

        // 查询商品信息
        List<Long> commodityIds = new ArrayList<>();
        for (OrderCommodity orderCommodity : orderCommodities) {
            commodityIds.add(orderCommodity.getCommodityId());
        }
        // 获取商品明细
        log.info("【中旅商城--APP订单支付--商品详情】，入参为：{}", JSON.toJSONString(commodityIds));
        List<CommodityDTO> commodityDTOList = commodityService.selectCommodityDTOListByIds(commodityIds);
        log.info("【中旅商城--APP订单支付--商品详情】，返参为：{}", JSON.toJSONString(commodityDTOList));
        Map<Long, CommodityDTO> collectommodityMap = commodityDTOList.stream().collect(Collectors.toMap(CommodityDTO::getId, commodityDTO -> commodityDTO, (k1, k2) -> k1));

        for (OrderCommodity orderCommodity : orderCommodities) {
            SupplierOrderSystemCommodityAddReq supplierOrderSystemCommodityAddReq = new SupplierOrderSystemCommodityAddReq();
            supplierOrderSystemCommodityAddReq.setSupplierId(collectommodityMap.get(orderCommodity.getCommodityId()).getSupplierId());
            supplierOrderSystemCommodityAddReq.setSupplierOrderType("1"); // 供应商订单类型
            supplierOrderSystemCommodityAddReq.setBusinessType(SystemBusinessType.COMMODITY.getCode()); // 业务类型
            supplierOrderSystemCommodityAddReq.setSaleType(SalesMethod.SINGLE_SALE.getCode()); // 销售方式
            supplierOrderSystemCommodityAddReq.setReserveTypeId(SupplierReserveTypeEnum.COMMODITY.getId()); // 预订类型
            supplierOrderSystemCommodityAddReq.setProductType(ProductType.MANUAL_ENTRY.getCode()); // 产品类型
            supplierOrderSystemCommodityAddReq.setSaleNumber(orderCommodity.getOrderId().toString()); // 销售单号
            supplierOrderSystemCommodityAddReq.setProductName(orderCommodity.getCommodityName()); // 产品名称
            supplierOrderSystemCommodityAddReq.setTotalFee(orderCommodity.getCommodityTotalPrice()); // 总金额
            supplierOrderSystemCommodityAddReq.setCurrency(Currency.HKD.getCurrency()); // 币种名称
            supplierOrderSystemCommodityAddReq.setCurrencyId(Currency.HKD.getCode()); // 币种id

            // 设置商品信息详情列表
            List<SupplierSystemOrderCommodityAddReq> supplierSystemOrderCommodityAddReqList = new ArrayList<>();
            SupplierSystemOrderCommodityAddReq addReq = new SupplierSystemOrderCommodityAddReq();
            // 订单id
            addReq.setOrderId(order.getId());
            // 客户备注
            addReq.setCustomerRemark(null);
            // 适合人群
            addReq.setSuitablePeople(null);
            // 供应商备注
            addReq.setSupplierRemark(null);

            // 商品信息详情列表
            List<SupplierSystemOrderCommodityDetailAddReq> reqList = new ArrayList<>();
            SupplierSystemOrderCommodityDetailAddReq commodityDetailAddReq = new SupplierSystemOrderCommodityDetailAddReq();
            commodityDetailAddReq.setOrderId(order.getId()); // 订单id
            commodityDetailAddReq.setCommodityName(orderCommodity.getCommodityName()); // 商品名称
            commodityDetailAddReq.setCommodityNumber(orderCommodity.getCommodityNumber()); // 商品编码
            commodityDetailAddReq.setNumber(orderCommodity.getNumber()); // 商品数量
            commodityDetailAddReq.setPrice(orderCommodity.getCommodityPrice()); // 商品单价
            commodityDetailAddReq.setPassengerName(null); // TODO 用户姓名
            reqList.add(commodityDetailAddReq);
            addReq.setSupplierSystemOrderCommodityDetailAddReqList(reqList);
            supplierSystemOrderCommodityAddReqList.add(addReq);

            // 商品信息列表
            supplierOrderSystemCommodityAddReq.setSupplierSystemOrderCommodityAddReqList(supplierSystemOrderCommodityAddReqList);
            supplierOrderSystemCommodityAddReq.setPayableAmount(orderCommodity.getCommodityTotalPrice());

            // 商品详情
            SupplierSystemOrderCommodityDetailAddReq detailAddReq = new SupplierSystemOrderCommodityDetailAddReq();
            // 订单id
            detailAddReq.setOrderId(order.getId());
            // 商品编号
            detailAddReq.setCommodityNumber(orderCommodity.getCommodityNumber());
            // 商品名称
            detailAddReq.setCommodityName(orderCommodity.getCommodityName());
            // 数量
            detailAddReq.setNumber(orderCommodity.getNumber());
            // 商品单价
            detailAddReq.setPrice(orderCommodity.getCommodityPrice());

            // collectommodityMap.get(orderCommodity.getCommodityId()).getSupplierId()
            log.info("【中旅商城--APP订单支付--新增供应商预订】，入参为:{}", JSONObject.toJSONString(supplierOrderSystemCommodityAddReq));
            supplierOrderService.addSystemCommodity(supplierOrderSystemCommodityAddReq, saleMan.getId());
        }
        /****************************************供应商预订单 end********************************************************/

        /****************************************财务中心新增收款记录 start********************************************************/
        List<BillAddCollectionReq> billAddCollectionReqs = new ArrayList<>();
        for (OrderCommodityCollection commodityCollection : orderCommodityCollections) {
            // 新增收款认款req
            BillAddCollectionReq billAddCollectionReq = new BillAddCollectionReq();
            billAddCollectionReq.setBillNumber(commodityCollection.getCollectionNumber()); // 收款单号
            billAddCollectionReq.setBusinessType(SystemBusinessType.COMMODITY.getCode());// 业务类型
            billAddCollectionReq.setCollectionWayId(req.getOrderCommodityPayDetailReqList().get(0).getCollectionWayId()); // 收款方式ID
            billAddCollectionReq.setCollectionWayName(req.getOrderCommodityPayDetailReqList().get(0).getCollectionWay());// 收款方式
            billAddCollectionReq.setCollectionTypeId(CollectionTypeIdCode.FULL.getCode());// 收款类型id 全款
            billAddCollectionReq.setCollectionTypeName(CollectionTypeIdCode.FULL.getMsg()); // 收款类型 全款
            billAddCollectionReq.setCollectionAmount(req.getOrderCommodityPayDetailReqList().get(0).getCollectionAmount());// 收款金额
            billAddCollectionReq.setCurrencyId(Currency.HKD.getCode());// 币种id
            billAddCollectionReq.setCurrencyName(Currency.HKD.getCurrency()); // 币种名称
            billAddCollectionReq.setExchangeRate(marketExchangeRate.doubleValue());// 汇率
            billAddCollectionReq.setCollectionTime(now);// 收款时间
//        String collectionCertificateJson = req.getOrderCommodityPayDetailReqList().get(0).getCollectionCertificateJson();
            List<FileJson> fileJsons = JSON.parseArray(commodityCollection.getCollectionCertificateJson(), FileJson.class);
            billAddCollectionReq.setCollectionVoucherJsonList(fileJsons);// 收款凭证json
            billAddCollectionReq.setSaleOrderNumber(order.getOrderNumber());//订单号
            billAddCollectionReq.setSaleOrderId(order.getId());//订单id
            billAddCollectionReq.setProductId(commodityIds);//产品id列表 商品id
            billAddCollectionReq.setProductNumber(commodityDTOList.get(0).getCommodityName()); // 产品编号/团号 商品名称
            billAddCollectionReq.setProductName(commodityDTOList.get(0).getCommodityNumber());//产品编号、团号 商品编号
            List<String> resourceInfo = new ArrayList<>();
            resourceInfo.add(commodityDTOList.get(0).getCommodityName());
            billAddCollectionReq.setResourceInfo(resourceInfo);// 资源信息列表 --- 商品名称?
            billAddCollectionReq.setSaleUserId(saleMan.getId());// 销售人员id
            billAddCollectionReq.setSaleUserName(saleMan.getEnName());// 销售人员名称
            billAddCollectionReq.setSaleDeptId(saleMan.getDeptId());//销售部门id
            billAddCollectionReq.setUserId(saleMan.getId());// 用户id（当前用户）
            billAddCollectionReqs.add(billAddCollectionReq);
        }
        log.info("【中旅商城--APP订单支付--新增财务中心收款记录】，入参为:{}", JSONObject.toJSONString(billAddCollectionReqs));
        iFinanceBillService.addCollection(billAddCollectionReqs);
        /****************************************财务中心新增收款记录 end********************************************************/

        /*********更新订单状态start*********/

        // 订单状态:1：待付款; 2：待发货; 3：待收货; 4：已完成; 5：已取消
        if (order.getDeliveryMode().intValue() == 2){
            order.setOrderStatus(6);
        }else {
            order.setOrderStatus(2);
        }
        // 付款状态:1：待支付;2：已付款
        order.setPaymentStatus(2);
        // 预订状态：1、确定预订 2、确认取消 3、待确认
        order.setScheduledStatus(1);
        // 取消状态 1、审批中 2、审批通过 3、审批未通过
        order.setCancelStatus(0);

        log.info("【中旅商城】支付成功，修改订单几个状态，入参为:{}", JSONObject.toJSONString(order));
        orderMapper.updateOrderById(order);
        /*********更新订单状态end*********/

        return Result.success(1);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result payOrder(OrderCommodityPayReq req, TokenUser tokenUser) {
        Order order = orderMapper.selectById(req.getId());
        if (Objects.isNull(order)) {
            return Result.failed(SystemError.MALL_MERCHANDISE_23033);
        }

        //获取当前用户信息
        UserDTO user = sysUserService.getUser(new UserDTO().setUsername(tokenUser.getUsername()));
        if (null == user) {
            return Result.failed(SystemError.USER_1002);
        }
        BigDecimal orderAmount = order.getOrderAmount();
        List<OrderCommodityPayDetailReq> orderCommodityPayDetailReqs = req.getOrderCommodityPayDetailReqList();
        if (req.getIsUnionpayDiscount().intValue() == NumberConstant.ONE.getValue().intValue() &&
                (null == req.getUnionpayDiscountId() || req.getUnionpayDiscountId().intValue() < NumberConstant.ONE.getValue().intValue())) {
            return Result.failed(SystemError.MALL_MERCHANDISE_23034);
        }
        BigDecimal marketExchangeRate = null;
        BigDecimal totalMoney = BigDecimal.ZERO;

        List<OrderCommodityCollection> orderCommodityCollections = Lists.newArrayList();

        for (OrderCommodityPayDetailReq orderCommodityPayDetailReq : orderCommodityPayDetailReqs) {
            OrderCommodityCollection orderCommodityCollection = EntityUtil.copy(orderCommodityPayDetailReq, OrderCommodityCollection.class);
            String paymentNumber = generatorPaymentNumber(LocalDateTime.now());
            orderCommodityCollection.setCollectionNumber(paymentNumber);
            orderCommodityCollection.setIsPos(req.getIsPos());
            orderCommodityCollection.setIsUnionpayDiscount(req.getIsUnionpayDiscount());
            orderCommodityCollection.setUnionpayDiscountId(req.getUnionpayDiscountId());
            orderCommodityCollection.setId(IdWorker.getId());
            orderCommodityCollection.setOrderId(order.getId());
            orderCommodityCollection.setCreateId(tokenUser.getId());
            orderCommodityCollection.setModifiedId(tokenUser.getId());
            orderCommodityCollection.setSalerId(tokenUser.getId());
            orderCommodityCollection.setSalerName(tokenUser.getUsername());
            orderCommodityCollection.setGmtCreate(LocalDateTime.now());
            orderCommodityCollection.setGmtModified(LocalDateTime.now());
            orderCommodityCollection.setIsDeleted(IsDeletedCode.NO.getCode());

            /******************************记录汇率 start*******************************/
            //获取汇率
            MainDataCurrencyQueryDTO exchangeRate = getExchangeRateByCurrencyId(orderCommodityPayDetailReq.getCurrencyId());
            //保证汇率存在
            if (exchangeRate == null || exchangeRate.getMarketExchangeRate() == null) {
                throw new BusinessException(SystemError.AIR_ORDER_15011, orderCommodityPayDetailReq.getCurrency());
            }
            marketExchangeRate = exchangeRate.getMarketExchangeRate();
            //当前汇率
            orderCommodityCollection.setExchangeRate(marketExchangeRate.doubleValue());
            BigDecimal divide = orderCommodityPayDetailReq.getCollectionAmount().multiply(marketExchangeRate).setScale(3, BigDecimal.ROUND_DOWN);

            // 数据库表无汇率值和汇率转换之后的金额字段，看需求是否需要增加字段
            //计算金额
            // orderCommodityCollection.setExchangeRateAfterMoney(divide);
            //汇率ID
            // orderCommodityCollection.setExchangeRateId(exchangeRate.getId());

            //累计金额
            totalMoney = totalMoney.add(divide);
            /*****************************记录汇率 end********************************/

            orderCommodityCollectionMapper.insert(orderCommodityCollection);
            orderCommodityCollections.add(orderCommodityCollection);
        }

        /****************************************供应商预订单 start********************************************************/
        //订单详情的金额需要<=实付金额
        if (order.getOrderAmount().compareTo(totalMoney) > 0) {
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23035);
        }

        // 查询订单商品信息
        QueryWrapper<OrderCommodity> orderCommodityQueryWrapper = new QueryWrapper<>();
        orderCommodityQueryWrapper.lambda().eq(OrderCommodity::getOrderId, req.getId());
        List<OrderCommodity> orderCommodities = orderCommodityMapper.selectList(orderCommodityQueryWrapper);
        if (CollectionUtils.isEmpty(orderCommodities)) {
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23033);
        }

        // 查询商品信息
        List<Long> commodityIds = new ArrayList<>();
        for (OrderCommodity orderCommodity : orderCommodities) {
            commodityIds.add(orderCommodity.getCommodityId());
        }
        List<CommodityDTO> commodityDTOList = commodityService.selectCommodityDTOListByIds(commodityIds);
        Map<Long, CommodityDTO> collectommodityMap = commodityDTOList.stream().collect(Collectors.toMap(CommodityDTO::getId, commodityDTO -> commodityDTO, (k1, k2) -> k1));

        for (OrderCommodity orderCommodity : orderCommodities) {
            SupplierOrderSystemCommodityAddReq supplierOrderSystemCommodityAddReq = new SupplierOrderSystemCommodityAddReq();
            supplierOrderSystemCommodityAddReq.setSupplierId(collectommodityMap.get(orderCommodity.getCommodityId()).getSupplierId());
            supplierOrderSystemCommodityAddReq.setSupplierOrderType("1");
            supplierOrderSystemCommodityAddReq.setBusinessType(SystemBusinessType.COMMODITY.getCode());
            supplierOrderSystemCommodityAddReq.setSaleType(SalesMethod.SINGLE_SALE.getCode());
            supplierOrderSystemCommodityAddReq.setReserveTypeId(SupplierReserveTypeEnum.COMMODITY.getId());
            supplierOrderSystemCommodityAddReq.setProductType(ProductType.MANUAL_ENTRY.getCode());
            supplierOrderSystemCommodityAddReq.setSaleNumber(orderCommodity.getOrderId().toString());
            supplierOrderSystemCommodityAddReq.setProductName(orderCommodity.getCommodityName());
            supplierOrderSystemCommodityAddReq.setTotalFee(orderCommodity.getCommodityTotalPrice());
            supplierOrderSystemCommodityAddReq.setCurrency("HKD");
            supplierOrderSystemCommodityAddReq.setPayableAmount(orderCommodity.getCommodityTotalPrice());

            // 商品详情
            SupplierSystemOrderCommodityDetailAddReq detailAddReq = new SupplierSystemOrderCommodityDetailAddReq();
            detailAddReq.setOrderId(order.getId());
            detailAddReq.setCommodityNumber(orderCommodity.getCommodityNumber());
            detailAddReq.setCommodityName(orderCommodity.getCommodityName());
            detailAddReq.setNumber(orderCommodity.getNumber());
            // detailAddReq.setPrice(collectommodityMap.get(orderCommodity.getCommodityId()));

            // collectommodityMap.get(orderCommodity.getCommodityId()).getSupplierId()
            supplierOrderService.addSystemCommodity(supplierOrderSystemCommodityAddReq, user.getId());
        }

        /****************************************供应商预订单 end********************************************************/

        return Result.success(1);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<OrderCommodityPayCallbackDetailReq> payCallback(NotifyConsumeReq req, TokenUser tokenUser) throws Exception {

        log.info("【中旅商城订单APP-支付订单】方法入参:{}", JSON.toJSONString(req));
        OrderCommodityPayCallbackDetailReq detailReq = new OrderCommodityPayCallbackDetailReq();
        try {

            // 查询订单
            Order order = orderMapper.selectOrderByOrderNumber(req.getOrderNumber());

            if (order == null) {
                return Result.failed(SystemError.MALL_MERCHANDISE_23033);
            }

            LocalDateTime nowLocalDateTime = LocalDateTime.now();
            if (nowLocalDateTime.isAfter(order.getPayExpireDate())) {
                // 支付超时
                throw new BusinessException(SystemError.MALL_MERCHANDISE_23038);
            }

            // 支付失败状态
            if (StringUtils.isEmpty(req.getOrderNumber()) || req.getOrderStatus().intValue() == PayOrderStatus.PAYMENT_ERROR.getStatus()
                    || "".equals(req.getPaymentAccount()) || req.getPaymentMethod() == null) {
                return Result.failed(SystemError.PAY_22001);
            }

            OrderCommodityPayReq commodityPayReq = new OrderCommodityPayReq();
            // 是否pos机
            commodityPayReq.setIsPos(0);
            // 银联优惠
            commodityPayReq.setUnionpayDiscountId(0L);
            // 是否银联优惠
            commodityPayReq.setIsUnionpayDiscount(0);
            ArrayList<OrderCommodityPayDetailReq> payDetailReqList = new ArrayList<>();
            // 支付订单明细
            OrderCommodityPayDetailReq payDetailReq = new OrderCommodityPayDetailReq();
            payDetailReq.setCollectionAmount(order.getOrderAmount()); // 收款金额
            payDetailReq.setCurrencyId(Long.parseLong(PayCurrency.HKD.getCode())); //币种id
            payDetailReq.setCurrency(PayCurrency.HKD.getName()); // 币种
            payDetailReq.setCollectionWayId(req.getPaymentMethod().longValue());
            String payMethod = PaymentMethod.getByCode(req.getPaymentMethod().intValue()).getName();
            payDetailReq.setCollectionWay(payMethod); // 收款方式
            payDetailReq.setPayer(req.getPaymentAccount());  // 收款账号
            payDetailReqList.add(payDetailReq);
            commodityPayReq.setOrderCommodityPayDetailReqList(payDetailReqList);
            commodityPayReq.setId(order.getId());
            log.info("【中旅商城订单--生成供应商预订--更新订单状态】，入参为：{}", JSONObject.toJSONString(commodityPayReq));
            if (null == tokenUser) {
                orderService.payAppOrder(commodityPayReq, payMethod);
            } else {
                List<OrderCommodityCollectionReq> collectionReqList = new ArrayList<>();
                OrderCommodityCollectionReq collectionReq = new OrderCommodityCollectionReq();
                // 收款单号
                collectionReq.setCollectionNumber(req.getPaymentAccount());
                // 订单id
                collectionReq.setOrderId(order.getId());
                // 是否pos机
                collectionReq.setIsPos(0);
                //
                collectionReq.setStandardAmount(new BigDecimal("0"));
                // 收款金额
                collectionReq.setCollectionAmount(order.getOrderAmount());
                // 币种id
                collectionReq.setCurrencyId(Long.parseLong(PayCurrency.HKD.getCode()));
                MainDataCurrencyQueryDTO exchangeRate = getExchangeRateByName(Long.parseLong(PayCurrency.HKD.getCode()));
                BigDecimal plannedExchangeRate = exchangeRate.getPlannedExchangeRate();//计划汇率
                // 悦换率
                collectionReq.setExchangeRate(plannedExchangeRate.doubleValue());
                // 币种名称
                collectionReq.setCurrency(PayCurrency.HKD.getName());
                // 是否银联优惠
                collectionReq.setIsUnionpayDiscount(0);
                // 银联优惠id
                collectionReq.setUnionpayDiscountId(0L);
                // 收款方式id
                collectionReq.setCollectionWayId(PaymentMethod.getByCode(req.getPaymentMethod().intValue()).getCode().longValue());
                // 收款方式
                collectionReq.setCollectionWay(PaymentMethod.getByCode(req.getPaymentMethod().intValue()).getName());
                // 付款方
                collectionReq.setPayer(req.getPaymentAccount());
                // 备注
                collectionReq.setRemark("");
                // 收款凭证JSON
                collectionReq.setCollectionCertificateJson("");
                UserDTO saleMan = getSaleMan(order, CompanyType.HK_CT.getCode(), nowLocalDateTime);
                // 销售id
                collectionReq.setSalerId(saleMan.getId());
                // 销售姓名
                collectionReq.setSalerName(saleMan.getFullName());
                // 状态
                collectionReq.setStatus(OrderCollectionStatus.UN_REJECT.getCode());
                // 驳回信息
                collectionReq.setRejectInfo("");
                // 创建人id
                collectionReq.setCreateId(tokenUser.getId());
                // 修改人id
                collectionReq.setModifiedId(tokenUser.getId());
                // 删除标识
                collectionReq.setIsDeleted(0);
                collectionReq.setGmtCreate(LocalDateTime.now());
                collectionReq.setGmtModified(LocalDateTime.now());
                collectionReqList.add(collectionReq);
                orderService.payment(order.getId(), collectionReqList, tokenUser.getId());
            }

            log.info("【中旅商城--APP订单支付--收货人信息】，入参为：{}", JSON.toJSONString(order.getId()));
            OrderConsigneeInfo consigneeInfoByOrder = orderConsigneeInfoMapper.findConsigneeInfoByOrder(order.getId());
            log.info("【中旅商城--APP订单支付--收货人信息】，返参为：{}", JSON.toJSONString(consigneeInfoByOrder));
            if (consigneeInfoByOrder == null) {
                return Result.failed(SystemError.GOODS_ORDER_ERROR_40008);
            }
            HashMap<String, String> templateParamMap = new HashMap<>();
            templateParamMap.put("orderid", order.getOrderNumber());
            templateParamMap.put("code", order.getSearchCode());
            log.info("【中旅商城订单】生成短信模板，发送国际、国内短信，模板内容:{}", JSONObject.toJSONString(templateParamMap));
//            if (SmsUtil.isDomestic(consigneeInfoByOrder.getConsigneeMobileAreaCodeId().toString())) {
//                // 发送短信,国际短信
//                SmsUtil.sendSms(consigneeInfoByOrder.getConsigneeMobileAreaCodeId() + consigneeInfoByOrder.getConsigneePhone(), "SMS_217419315", templateParamMap);
//            } else {
//                // 发送短信,国内短信
//                SmsUtil.sendSms(consigneeInfoByOrder.getConsigneeMobileAreaCodeId() + consigneeInfoByOrder.getConsigneePhone(), "SMS_217429256", templateParamMap);
//            }

            // 获取订单商品详细
            OrderCommodity orderCommodity = orderCommodityMapper.selectCommodityById(order.getId());
            if (orderCommodity == null) {
                return Result.failed(SystemError.MALL_MERCHANDISE_23000);
            }

            detailReq.setOrderNumber(order.getId().toString());
            detailReq.setCommodityName(orderCommodity.getCommodityName());
            detailReq.setPaymentMethod(PaymentMethod.getByCode(req.getPaymentMethod().intValue()).getName());
            detailReq.setOrderStatus(OrderPaymentStatus.getOrderPaymentStatusName(order.getOrderStatus()));
            detailReq.setSearchCode(order.getSearchCode());
            updateStatusToAppUser(order.getId());
            log.info("【中旅商城订单】支付成功，返回内容req:{}", JSONObject.toJSONString(detailReq));
        } catch (BusinessException e) {
            log.error("【中旅商城订单APP-回调支付】唤起支付失败失败,error:{}", e.getMessage(), e);
            throw new BusinessException(SystemError.PAY_22001);
        } catch (Exception e) {
            log.error("【中旅商城订单APP-回调支付】系统异常,error:{}", e.getMessage(), e);
            throw new BusinessException(SystemError.PAY_22001);
        }
        return Result.success(detailReq);
    }

    /**
     * 根据币种ID获取汇率，获取汇率,
     *
     * @return
     */
    private MainDataCurrencyQueryDTO getExchangeRateByCurrencyId(Long currencyId) {
        MainDataCurrencyUpdateStatusReq mainDataCurrencyUpdateStatusReq = new MainDataCurrencyUpdateStatusReq();
        mainDataCurrencyUpdateStatusReq.setId(currencyId);
        Result<MainDataCurrencyQueryDTO> queryCurrencyRateResult = mainDataCurrencyService.query(mainDataCurrencyUpdateStatusReq);
        if (!queryCurrencyRateResult.isSuccess()) {
            SystemError defined = SystemError.getDefined(queryCurrencyRateResult.getCode());
            throw new BusinessException(defined);
        }
        return queryCurrencyRateResult.getData();
    }

    @Override
    public PageResponse<OrderPageListDTO> orderCommodityPage(OrderPageListReq req, Long userId) {
        if (null == req || null == req.getDeliveryMode()) {
            throw new BusinessException(SystemError.SYS_402);
        }
        if (null == userId) {
            throw new BusinessException(SystemError.SYS_406);
        }
        IPage<OrderPageListDTO> page = new Page<OrderPageListDTO>(req.getPageNo(), req.getPageSize());
        IPage<OrderPageListDTO> iPage = orderMapper.findOrderPageByCondition(page, req);
        List<OrderPageListDTO> recordsList = iPage.getRecords();
        getCommodityDetails(recordsList);
        List<OrderPageListDTO> pageDTOList = EntityUtil.copyList(recordsList, OrderPageListDTO.class);
        return new PageResponse<>(pageDTOList, iPage.getCurrent() == 1,
                iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()),
                iPage.getTotal(), iPage.getCurrent(), iPage.getSize());

    }

    @Override
    public OrderDetailDTO getAppOrderCommodityDetail(Long orderId, Integer type, TokenUser tokeneUsr) {
        // 参数校验
        if (orderId == null || type == null) {
            throw new BusinessException(SystemError.SYS_402);
        }
        // 获取订单详情分页
        OrderDetailDTO dbOrderDetailDTO = orderMapper.findOrderCustomerInfoByOrderId(orderId);
        if (dbOrderDetailDTO == null) {
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23000);
        }
        // 获取订单商品信息详细
        List<OrderCommodityPageListDetailDTO> dbOrderCommodityList = orderCommodityMapper.findCommodityDetailsByOrderId(Arrays.asList(orderId));
        if (type == 0) {
            // 查询商品收款明细
            List<OrderCommodityCollectionDTO> dbCommodityCollectionList = orderCommodityCollectionMapper.findOrderCommodityCollectionByOrderId(orderId);
            // 查询商品退款记录
            List<OrderCommodityRefundDTO> dbCommodityRefundList = orderCommodityRefundMapper.findOrderCommodityRefundByOrderId(orderId);

            dbOrderDetailDTO.setOrderCommodityCollectionDTOList(dbCommodityCollectionList);
            dbOrderDetailDTO.setOrderCommodityRefundDTOList(dbCommodityRefundList);
        }
        dbOrderDetailDTO.setOrderCommodityPageListDetailDTOList(dbOrderCommodityList);
        return dbOrderDetailDTO;
    }

    @Override
    public OrderDetailDTO getOrderCommodityDetail(Long orderId, Integer type, TokenUser tokeneUsr) {
        // 参数校验
        if (orderId == null || type == null) {
            throw new BusinessException(SystemError.SYS_402);
        }
        if (tokeneUsr == null) {
            throw new BusinessException(SystemError.SYS_406);
        }
        // 获取订单详情分页
        OrderDetailDTO dbOrderDetailDTO = orderMapper.findOrderCustomerInfoByOrderId(orderId);
        if (dbOrderDetailDTO == null) {
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23000);
        }

        // 获取订单商品信息详细
        List<OrderCommodityPageListDetailDTO> dbOrderCommodityList = orderCommodityMapper.findCommodityDetailsByOrderId(Arrays.asList(orderId));
        if (type == 0) {
            // 查询商品收款明细
            List<OrderCommodityCollectionDTO> dbCommodityCollectionList = orderCommodityCollectionMapper.findOrderCommodityCollectionByOrderId(orderId);
            // 查询商品退款记录
            List<OrderCommodityRefundDTO> dbCommodityRefundList = orderCommodityRefundMapper.findOrderCommodityRefundByOrderId(orderId);

            dbOrderDetailDTO.setOrderCommodityCollectionDTOList(dbCommodityCollectionList);
            dbOrderDetailDTO.setOrderCommodityRefundDTOList(dbCommodityRefundList);
        }
        dbOrderDetailDTO.setOrderCommodityPageListDetailDTOList(dbOrderCommodityList);
        return dbOrderDetailDTO;
    }

    @Override
    public Result<OrderDetailDTO> queryOrderByOrderNumAndSearchCode(String orderNumber, String searchCode) {
        log.info("【中旅商城--app手机查单--start】，入参为:orderNumber:{},searchCode:{}", orderNumber, searchCode);
        if (StringUtils.isEmpty(orderNumber) || StringUtils.isEmpty(searchCode)) {
            throw new BusinessException(SystemError.SYS_402);
        }
        // 根据订单编号和查询号码获取订单id
        Order order = orderMapper.findOrderIdByOrderNumerAndSearchCode(orderNumber, searchCode);
        log.info("【中旅商城--app手机查单--查询订单信息】，返参为:{}", JSON.toJSONString(order));
        if (null == order) {
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23033);
        }
        // 查询订单明细
        OrderDetailDTO dbOrderDetailDTO = orderMapper.findOrderCustomerInfoByOrderId(order.getId());
        log.info("【中旅商城--app手机查单--查询订单明细】，返参为:{}", JSON.toJSONString(dbOrderDetailDTO));
        if (dbOrderDetailDTO == null) {
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23000);
        }
        // 根据订单id查询商品明细
        List<OrderCommodityPageListDetailDTO> dbOrderCommodityList = orderCommodityMapper.findCommodityDetailsByOrderId(Arrays.asList(order.getId()));
        log.info("【中旅商城--app手机查单--查询商品明细】，返参为:{}", JSON.toJSONString(dbOrderCommodityList));
        // 根据订单id查询收款明细
        List<OrderCommodityCollectionDTO> dbCommodityCollectionList = orderCommodityCollectionMapper.findOrderCommodityCollectionByOrderId(order.getId());
        log.info("【中旅商城--app手机查单--查询收款明细】，返参为:{}", JSON.toJSONString(dbCommodityCollectionList));
        // 根据订单id查询退款明细
        List<OrderCommodityRefundDTO> dbCommodityRefundList = orderCommodityRefundMapper.findOrderCommodityRefundByOrderId(order.getId());
        log.info("【中旅商城--app手机查单--查询退款明细】，返参为:{}", JSON.toJSONString(dbCommodityRefundList));
        if (order.getDeliveryMode() == 1) { // 物流配送
            QueryWrapper<OrderConsigneeInfo> consigneeInfoQueryWrapper = new QueryWrapper<>();
            consigneeInfoQueryWrapper.eq("order_id", order.getId());
            OrderConsigneeInfo orderConsigneeInfo = orderConsigneeInfoMapper.selectOne(consigneeInfoQueryWrapper);
            log.info("【中旅商城--app手机查单--查询收货人信息】，返参为:{}", JSON.toJSONString(orderConsigneeInfo));
            if (null != orderConsigneeInfo) {
                // consigneeAddress、consigneeEmail、consigneePhone、consignee
                dbOrderDetailDTO.setConsigneeAddress(orderConsigneeInfo.getConsigneeAddress());
                dbOrderDetailDTO.setConsigneeEmail(orderConsigneeInfo.getConsigneeEmail());
                dbOrderDetailDTO.setConsigneePhone(orderConsigneeInfo.getConsigneePhone());
                dbOrderDetailDTO.setConsignee(orderConsigneeInfo.getConsignee());
            }
        } else if (order.getDeliveryMode() == 2) { // 门店自提
            // shipper、shipperPhone、shipperStoreId、shipperStoreName、shipperStoreAddress
            QueryWrapper<OrderShipperInfo> orderShipperInfoQueryWrapper = new QueryWrapper<>();
            orderShipperInfoQueryWrapper.eq("order_id", order.getId());
            OrderShipperInfo orderShipperInfo = orderShipperInfoMapper.selectOne(orderShipperInfoQueryWrapper);
            log.info("【中旅商城--app手机查单--门店自提--查询收货人信息】，返参为:{}", JSON.toJSONString(orderShipperInfo));
            if (null != orderShipperInfo) {
                dbOrderDetailDTO.setShipper(orderShipperInfo.getShipper());
                dbOrderDetailDTO.setShipperPhone(orderShipperInfo.getShipperPhone());
                dbOrderDetailDTO.setShipperStoreId(orderShipperInfo.getShipperStoreId());
                dbOrderDetailDTO.setShipperStoreName(orderShipperInfo.getShipperStoreName());
                dbOrderDetailDTO.setShipperStoreAddress(orderShipperInfo.getShipperStoreAddress());
            }
        }
        dbOrderDetailDTO.setOrderCommodityCollectionDTOList(dbCommodityCollectionList);
        dbOrderDetailDTO.setOrderCommodityRefundDTOList(dbCommodityRefundList);
        dbOrderDetailDTO.setOrderCommodityPageListDetailDTOList(dbOrderCommodityList);
        log.info("【中旅商城--app手机查单--end】");
        return Result.success(dbOrderDetailDTO);

    }

    @Override
    public Result<OrderDTO> info(Long id) {
        log.info("【中旅商城--支付详情--start】,入参为:{}", id);
        Order order = orderMapper.selectOrderById(id);
        List<OrderCommodityCollection> commodityCollections = orderCommodityCollectionMapper.selectCollectionByOrderId(id);
        OrderDTO orderDTO = EntityUtil.copy(order, OrderDTO.class);
        if (CollectionUtils.isNotEmpty(commodityCollections)) {
            orderDTO.setPayMethod(commodityCollections.get(0).getCollectionWay());
        }
        orderDTO.setPayTime(order.getGmtCreate());
        log.info("【中旅商城--支付详情--end】,返参为:{}", JSON.toJSONString(orderDTO));
        return Result.success(orderDTO);
    }

    @Override
    public CallPayDTO getCallPayInfo(Long id) {
        Order order = orderMapper.selectOne(Wrappers.<Order>lambdaQuery()
                .eq(Order::getId, id)
                .eq(Order::getPaymentStatus, OrderPaymentStatus.UN_PAYMENT.getCode())
                .eq(Order::getIsDeleted, IsDeletedCode.NO.getCode())
                .select(Order::getId, Order::getOrderNumber, Order::getOrderAmount, Order::getPayExpireDate, Order::getSaleUserId, Order::getPaymentStatus));
        if (null == order) {
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23033);
        }
        CallPayDTO callPayDTO = EntityUtil.copy(order, CallPayDTO.class);
        callPayDTO.setSalesmanId(order.getSaleUserId());
        callPayDTO.setOrderValidTime(order.getPayExpireDate());
        callPayDTO.setTotalFee(order.getOrderAmount());
        callPayDTO.setCurrency(PayCurrency.HKD);
        callPayDTO.setSubject("中旅商城订单支付");
        callPayDTO.setBody("中旅商城订单支付");
        return callPayDTO;
    }

    @Override
    public Result<QueryQuotaDTO> queryQuota(QueryQuotaReq req) {
        log.info("【中旅商城--支付--查询内部挂账--start】，入参为:{}", JSON.toJSONString(req));
        Order order = orderMapper.selectOrderById(req.getOrderId());
        log.info("【中旅商城--支付--查询内部挂账--start】，返参为:{}", JSON.toJSONString(order));
        if (Objects.isNull(order)) {
            return Result.failed(SystemError.SYS_411);
        }
        com.ctshk.rpc.finance.req.onaccount.QueryQuotaReq queryQuotaReq = new com.ctshk.rpc.finance.req.onaccount.QueryQuotaReq();
        queryQuotaReq.setCurrencyId(CurrencyIdCode.HKD.getCode()); // 币种
        if (order.getOrderSourceType().intValue() == 1) {
            queryQuotaReq.setAccountType(2); // 散客，内部挂账
            Long userId = req.getUserId();
            UserDTO userDTO = sysUserService.queryCacheUser(userId);
            queryQuotaReq.setDeptId(userDTO.getDeptId());
        } else if (order.getOrderSourceType().intValue() == 2) {
            queryQuotaReq.setAccountType(1); // 大客户，挂账
            queryQuotaReq.setAccountId(req.getAccountId());
        }
        log.info("【中旅商城--支付--查询内部挂账】，入参为:{}", JSON.toJSONString(queryQuotaReq));
        Result<com.ctshk.rpc.finance.dto.onaccount.QueryQuotaDTO> queryQuotaDTOResult = onAccountCurrencyQuotaService.queryQuota(queryQuotaReq);
        log.info("【中旅商城--支付--查询内部挂账】，返参为:{}", JSON.toJSONString(queryQuotaDTOResult));
        if (queryQuotaDTOResult.getCode() != 0) {
            throw new BusinessException(SystemError.LOCAL_FUN_18008, queryQuotaDTOResult.getMsg());
        }
        com.ctshk.rpc.finance.dto.onaccount.QueryQuotaDTO data = queryQuotaDTOResult.getData();
        QueryQuotaDTO queryQuotaDTO = EntityUtil.copy(data, QueryQuotaDTO.class);
        log.info("【中旅商城--支付--查询内部挂账--end】");
        return Result.success(queryQuotaDTO);
    }

    public MyOrderDetailDTO buildEsOrderDTO(Long orderId) {
        Order order = baseMapper.selectById(orderId);
        MyOrderDetailDTO orderDTO = EntityUtil.copy(order, MyOrderDetailDTO.class);
        List<OrderCommodityPageListDetailDTO> commodityDetailsByOrderId = orderCommodityMapper.findCommodityDetailsByOrderId(Lists.newArrayList(orderDTO.getId()));
        orderDTO.setOrderCommodityPageListDetailDTOList(commodityDetailsByOrderId);
        return orderDTO;
    }

    /**
     * 异步发送订单数据到个人中心
     *
     * @param orderId 订单Id
     */
    public void sendOrderToAppUser(Long orderId) {
        CompletableFuture.runAsync(() -> {
            try {
                MyOrderDetailDTO orderDTO = buildEsOrderDTO(orderId);
                orderEsService.saveOrderToEs(orderDTO, SystemBusinessType.COMMODITY);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 异步更新订单状态到个人中心
     */
    public void updateStatusToAppUser(Long orderId) {
        CompletableFuture.runAsync(() -> {
            try {
                Order order = baseMapper.selectById(orderId);
                orderEsService.updateStatusToEs(order.getId(), SystemBusinessType.COMMODITY.getCode(),
                        order.getOrderStatus(), order.getPaymentStatus(), order.getScheduledStatus(),
                        order.getCancelStatus());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}